LeetCode.145 Binary Tree Postorder Tranversal

来源:互联网 发布:淘宝返利机器人怎么做 编辑:程序博客网 时间:2024/06/05 23:07

题目:

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(非递归实现-List的巧妙插入-推荐):

/** * 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> list=new ArrayList<Integer>();        if(root==null) return list;        Stack<TreeNode> stack=new Stack<TreeNode>();        stack.push(root);        while(!stack.empty()){            root=stack.pop();            if(root.left!=null){                stack.push(root.left);            }            if(root.right!=null){                stack.push(root.right);            }            //每次将元素插入最前面,因为出栈的顺序为“根右左”,那么插入的话就是“左右根”            list.add(0,root.val);        }                return list;    }}


分析2(两个Stack实现-易理解):

/** * 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) {        //给定二叉树,实现后序遍历        //思路:巧妙使用两个stack实现,一个用来遍历,一个用来存储                List<Integer> list =new ArrayList<>();        if(root==null) return list;                Stack<TreeNode> inputStack=new Stack<>();        Stack<TreeNode> outputStack=new Stack<>();        while(root!=null||!inputStack.empty()){            //使用两个stack来存储相应的节点,inputStack作为输出            if(root!=null){                inputStack.push(root);                outputStack.push(root);                //将左孩子先存入                root=root.right;            }else{                //右子树存储完毕,存储左子树                root=inputStack.pop();                root=root.left;            }        }        //将最后的结果输出        while(!outputStack.empty()){            list.add(outputStack.pop().val);        }                return list;    }}




原创粉丝点击