1. 二叉树的递归遍历
144. 二叉树的前序遍历https://leetcode.cn/problems/binary-tree-preorder-traversal/94. 二叉树的中序遍历https://leetcode.cn/problems/binary-tree-inorder-traversal/145. 二叉树的后续遍历https://leetcode.cn/problems/binary-tree-postorder-traversal/二叉树的深度优先遍历,是一个递归式的算法,对于递归,需要注意的就是每次递归的返回值,以及每次递归需要的参数,以及中止条件和进入递归的判断逻辑。
代码
- 前序
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();pre(root, list);return list;}private void pre(TreeNode root, List<Integer> result) {if (root == null)return;result.add(root.val);pre(root.left, result);pre(root.right, result);}
}
- 中序
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();inorder(root, list);return list;}private void inorder(TreeNode root, List<Integer> result) {if (root == null)return;inorder(root.left, result);result.add(root.val);inorder(root.right, result);}
}
- 后序
class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();postorder(root, list);return list;}private void postorder(TreeNode root, List<Integer> result) {if (root == null)return;postorder(root.left, result);postorder(root.right, result);result.add(root.val);}
}
2. 二叉树的迭代遍历
使用栈进行迭代遍历
- 前序
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null)return result;Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();result.add(node.val);if (node.right != null) {stack.push(node.right);}if (node.left != null) {stack.push(node.left);}}return result;}
}
- 中序
中序遍历需要注意:
中序遍历是先一路找到最左的,然后输出,每次输出就是处理一个node,输出后就得找到右节点的最左的。
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null)return result;Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;while (cur != null || !stack.isEmpty()) {if (cur != null) {stack.push(cur);cur = cur.left;} else {cur = stack.pop();result.add(cur.val);cur = cur.right;}}return result;}
}
- 后序
class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null)return result;Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();result.add(node.val);if (node.left != null) {stack.push(node.left);}if (node.right != null) {stack.push(node.right);}}Collections.reverse(result);return result;}
}