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 preorderTraversal(TreeNode root) {
List list = new ArrayList<>();
pre(root, list);
return list;
}
private void pre(TreeNode root, List result) {
if (root == null)
return;
result.add(root.val);
pre(root.left, result);
pre(root.right, result);
}
}
class Solution {
public List inorderTraversal(TreeNode root) {
List list = new ArrayList<>();
inorder(root, list);
return list;
}
private void inorder(TreeNode root, List result) {
if (root == null)
return;
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}
class Solution {
public List postorderTraversal(TreeNode root) {
List list = new ArrayList<>();
postorder(root, list);
return list;
}
private void postorder(TreeNode root, List result) {
if (root == null)
return;
postorder(root.left, result);
postorder(root.right, result);
result.add(root.val);
}
}
使用栈进行迭代遍历
class Solution {
public List preorderTraversal(TreeNode root) {
List result = new ArrayList<>();
if (root == null)
return result;
Stack 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 inorderTraversal(TreeNode root) {
List result = new ArrayList<>();
if (root == null)
return result;
Stack 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 postorderTraversal(TreeNode root) {
List result = new ArrayList<>();
if (root == null)
return result;
Stack 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;
}
}