美文网首页
145. Binary Tree Postorder Trave

145. Binary Tree Postorder Trave

作者: namelessEcho | 来源:发表于2017-10-04 00:29 被阅读0次

同样的遍历过程,可以考虑用一个Stack保存先序遍历的结果,随后将stack内的值逐个POP。这里要求先左再右,如果在原有的遍历过程中仍然是以左半部分为优先的话,在pop后会变成右先左后,所以要从右边开始。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        TreeNode cur = root;
        while(!stack1.isEmpty()||cur!=null)
        {
            while(cur!=null)
            {
                stack2.push(cur.val);
                stack1.push(cur);
                cur=cur.right;
            }
            cur=stack1.pop().left;
        }
        while(!stack2.isEmpty())
        {
            result.add(stack2.pop());
        }
        return result ;
    }
}

相关文章

网友评论

      本文标题:145. Binary Tree Postorder Trave

      本文链接:https://www.haomeiwen.com/subject/kalqyxtx.html