[LeetCode]: 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 ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> arrResult = new ArrayList<Integer>();
        return AddNode(root,arrResult);
    }
    
    public ArrayList<Integer> AddNode(TreeNode root,ArrayList<Integer> arrTotal) {
        if(root == null){
            return arrTotal;
        }

        AddNode(root.left , arrTotal);
        AddNode(root.right , arrTotal);
        arrTotal.add(root.val);
        return arrTotal;
    }

 

思路2:广度优先搜索的变形,采用栈来记录节点

其中关键的一个点就是:当某一个节点的左子树或右子树不为空的时候,

     - 需要将左子树或者右子树也加到这个栈里面

     - 同时还要将原节点对应的左右子树置成null,这样再次遍历栈时,再回到那个节点才不会引起无限循环

    public ArrayList<Integer> postorderTraversal(TreeNode root) {

        ArrayList<Integer> arrResult = new ArrayList<Integer>();
        Stack<TreeNode> staTemp = new Stack<TreeNode>();
        Stack<TreeNode> staResult= new Stack<TreeNode>();
        
        if(root == null){
            return arrResult;
        }

        staTemp.push(root);
        while(!staTemp.empty()){
            TreeNode nodeTemp = staTemp.peek();
            
            if(nodeTemp.left == null && nodeTemp.right == null){
                arrResult.add(nodeTemp.val);
                staTemp.pop();
            }
            else{
                if(nodeTemp.right != null){
                    staTemp.push(nodeTemp.right);
                    nodeTemp.right = null;
                }
                
                if(nodeTemp.left != null){
                    staTemp.push(nodeTemp.left);
                    nodeTemp.left = null;
                }
            }
            
        }
        
        
        return arrResult;
    }

 

转载于:https://www.cnblogs.com/savageclc26/p/4864626.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值