遍历法:
经典递归三步带走
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res);
return res;
}
public void dfs(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
dfs(root.left, res);
dfs(root.right, res);
res.add(root.val);
}
}
迭代法:
正面迭代,后序遍历有个不太好处理的点是,栈中的元素弹出以后,要判断下右边节点是否已经遍历完成,因为只有右边也结束以后,才能把当前节点加进去。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> s = new Stack<>();
TreeNode pre = null;
while (!s.empty() || root != null) {
if (root != null) {
s.push(root);
root = root.left;
} else {
root = s.peek();
if (root.right == null || root.right == pre) {
s.pop();
res.add(root.val);
pre = root;
root = null;
} else {
root = root.right;
}
}
}
return res;
}
}
先序遍历反转,因为先序遍历是中左右、后序遍历是左中右,将先序遍历改成中右左即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> s = new Stack<>();
s.push(root);
while (!s.empty()) {
root = s.pop();
res.add(root.val);
if (root.left != null) {
s.push(root.left);
}
if (root.right != null) {
s.push(root.right);
}
}
Collections.reverse(res);
return res;
}
}