Leetcode: Binary Tree Postorder Transversal

时间:2023-03-09 16:43:17
Leetcode: Binary Tree Postorder Transversal
Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively?

难度:70

recursive方法很直接:

 public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
helper(root, res);
return res;
}
private void helper(TreeNode root, ArrayList<Integer> res)
{
if(root == null)
return;
helper(root.left,res);
helper(root.right,res);
res.add(root.val);
}

Iterative 最优做法:

pre-order traversal is root-left-right.

post-order traversal is left-right-root.

We can modify pre-order traversal to be root-right-left, and traverse the tree.

Finally, we reverse the output by the modified pre-order traversal to get post-order traversal.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode p = root;
while (p!=null || !stack.isEmpty()) {
if (p != null) {
stack.push(p);
res.addFirst(p.val);
p = p.right;
}
else {
TreeNode node = stack.pop();
p = node.left;
}
}
return res;
}
}

第一次Iterative的做法就没有那么strait forward的了,需要额外用一个ArrayList<TreeNode>来记录节点的访问情况

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
ArrayList<TreeNode> visited = new ArrayList<TreeNode>();
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
stack.push(root);
while (root != null || !stack.isEmpty()) {
if (root.left != null && !visited.contains(root.left)) {
stack.push(root.left);
root = root.left;
}
else if (root.right != null && !visited.contains(root.right)) {
stack.push(root.right);
root = root.right;
}
else {
visited.add(root);
res.add(stack.pop().val);
root = stack.peek();
}
}
return res;
}
}