问题:
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].
二叉树的后序遍历,我在Leetcode上做过的最简单的题。
解法1:递归
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer>a=new ArrayList<Integer>();
if (root==null)
return a;
a.addAll(postorderTraversal(root.left));
a.addAll(postorderTraversal(root.right));
a.add(root.val);
return a;
}
}
解法二:迭代
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer>a=new ArrayList<Integer>();
if (root==null)
return a;
Stack<TreeNode>stack1=new Stack<TreeNode>();
Stack<TreeNode>stack2=new Stack<TreeNode>();
stack1.add(root);
while (!stack1.empty())
{
TreeNode t=stack1.pop();
if (t.left!=null)
stack1.add(t.left);
if (t.right!=null)
stack1.add(t.right);
stack2.add(t);
}
while (!stack2.empty())
{
a.add(stack2.pop().val);
}
return a;
}
}