【LeetCode】Path Sum 2 --java 二叉数 深度遍历,保存路径

本文介绍了一个基于栈实现的PathSum算法,该算法用于查找二叉树中所有从根节点到叶子节点路径上的节点值之和等于给定目标值的路径。通过遍历二叉树并利用栈来保存路径,当遇到叶子节点时,检查路径和是否等于目标值,并返回所有符合条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Path SUm 1中(http://www.cnblogs.com/hitkb/p/4242822.html

我们采用栈的形式保存路径,每当找到符合的叶子节点,就将栈内元素输出。注意存在多条路径的情况。

 public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>>list=new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        int total = 0;
        if (root == null)
            return list;
        TreeNode qNode=root;
        while (root != null) {

            while (root.left != null) {
                stack.push(root);
                total += root.val;
                root = root.left;
            }//左节点压栈
            while (root != null && (root.right == null || root.right == qNode)) {//||前面是判断是否是叶子节点,后面是弹出右节点
                
                if(root.right==null&&root.left==null){
                    if((total+root.val)==sum){//此处是探测当前访问加上最终的叶子节点,是否等于输入。
                        list.add(getstack(stack,root.val));
                    }
                }
                qNode = root;// 记录上一个已输出节点
                if (stack.empty())
                    return list;
                root = stack.pop();
                total-=root.val;
            }
            stack.push(root);
            total+=root.val;
            root = root.right;

        }

        return list;
    }
    /*统计栈内元素
     * 
     * 
     */
    public  List<Integer> getstack(Stack<TreeNode>stack,Integer a){
        Stack<TreeNode>stack2=(Stack<TreeNode>) stack.clone();
        List<Integer>list=new ArrayList<>();
        list.add(a);
        while(!stack2.isEmpty()){
            TreeNode ouTreeNode=stack2.pop();
            list.add(0, ouTreeNode.val);
        }
        return list;
    }

 

转载于:https://www.cnblogs.com/hitkb/p/4243408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值