Java语言用递归和非递归实现二叉树的后序遍历

目录

1.递归实现

2.非递归实现(借助栈)


1.递归实现

/**
 * 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<>();
        print(list,root);
        return list;
    }
    public static void print(List<Integer> list,TreeNode root){
        if(root == null){
            return;
        }
        print(list,root.left);
        print(list,root.right);
        list.add(root.val);
    }
}

2.非递归实现(借助栈)

/**
 * 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<>();
        if(root == null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode pre = null;
        while(!stack.isEmpty()){
            TreeNode cur = stack.peek();
            //前一条件是指拿出栈顶元素,若栈顶元素的左右孩子都为空,就直接将该结点入到list集合中
            //后一条件是指栈顶元素的左右孩子都已经入到list集合中了,此时需要将cur结点入到list集合中
            if((cur.left==null&&cur.right==null)||(pre!=null&&(cur.left==pre||cur.right==pre))){
                list.add(cur.val);
                pre = cur;
                cur = stack.pop();
            }else{
                //注意先将右孩子入栈(后序遍历)
                if(cur.right!=null){
                    stack.push(cur.right);
                }
                if(cur.left!=null){
                    stack.push(cur.left);
                }
            }
        }
        return list;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值