找二叉树的左下角(递归法 要回溯) 路经总和

要找到二叉树的最大深度,才能更新res值,遍历采用左右,这样就能先遍历左结点,如果没有左节点再更新右结点

class Solution {
    int maxDepth=0;
    int res;
    public void travel(TreeNode root,int Depth){
        if(root.left==null&&root.right==null){
            if(Depth>maxDepth){
                maxDepth=Depth;
                res= root.val;
            }
            return;//遍历到叶子节点就结束
        }
        if(root.left!=null){
            Depth++;
            travel(root.left,Depth);//递
            Depth--;//回溯
        }
        if(root.right!=null){
            Depth++;
            travel(root.right,Depth);//递
            Depth--;//回溯
        }
        
    }
    public int findBottomLeftValue(TreeNode root) {
        travel(root,1);
        return res;
    }
}

路径总和

主要是找到了路径就直接返回true,递归的递前进行运算的话,归后要做逆运算。

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null) return false;
        targetSum-=root.val;
        if(root.left==null&&root.right==null&&targetSum==0) return true;
        if(root.left!=null){
            boolean left=hasPathSum(root.left,targetSum);
            if(left) return true;
        }
        if(root.right!=null){
            boolean right=hasPathSum(root.right,targetSum);
            if(right) return true;
        }
        return false;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值