題目[Binary Tree Postorder Traversal](145. Binary Tree Postorder Traversal)
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?
1,遞歸
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
dfs(root,result);
return result;
}
private void dfs(TreeNode root, List<Integer> result){
if(root == null){
return;
}
dfs(root.left,result);
dfs(root.right,result);
result.add(root.val);
}
2,非遞歸一
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<Integer>();
if(root == null){
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode node = stack.pop();
result.addFirst(node.val);
if(node.left != null){
stack.push(node.left);
}
if(node.right != null){
stack.push(node.right);
}
}
return result;
}
3,非遞歸二
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<Integer>();
if(root == null){
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
TreeNode tempNode = null;
boolean visited = false;
int height = 0;
do{
while(node != null ){
stack.push(node);
node = node.left;
}
tempNode = null;
visited = true;
while(!stack.empty() && visited){
node = stack.peek();
if(node.right == tempNode){
result.add(node.val);
tempNode = node;
stack.pop();
}else{
node = node.right;
visited = false;
}
}
}while(!stack.empty());
return result;
}