[leetcode]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].
二叉树的后序遍历,我在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 postorderTraversal(TreeNode root) {
        ArrayLista=new ArrayList();
        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 postorderTraversal(TreeNode root) {
         ArrayLista=new ArrayList();
        if (root==null)
            return a;
        Stackstack1=new Stack();
        Stackstack2=new Stack();
        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;
    }
}

你可能感兴趣的:([leetcode]binary-tree-postorder-traversal)