判断二叉树的路径和是否和给定数值相等

package niuke.day1;

import java.util.Stack;
/*Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,

             5
            / \
           4   8
          /   / \
         11  13  4
        /  \      \
       7    2      1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22. */

//其实本题并没有重复的子问题,无需考虑动态规划,单纯的递归完全可以解决问题

public class Path_Sum {
     public static void main(String[] args) {
         TreeNode t1 = new TreeNode(1);
         TreeNode t2 = new TreeNode(2);
         t1.right = t2;
         System.out.println(hasPathSum(t1, 3));
        
        
    }
       static Stack<TreeNode> s = new Stack<>();  //本题利用栈替代了递归的过程,事实证明我还是不擅长递归
       static boolean flag = false;    //定义标志位
     public static boolean hasPathSum(TreeNode root, int sum) {
         if(root != null)
             s.push(root);
         while(!s.isEmpty() && flag != true) { //当栈不为空或者还没有找到符合条件的路径则一直循环
             TreeNode temp = s.pop();
             if(temp.val == sum && temp.left == null && temp.right == null) {
                 flag = true;    //正好是叶子节点,又恰好满足条件则修改标志位
             }
             if(temp.left != null ) {
                 temp.left.val += temp.val;  
                 hasPathSum(temp.left, sum);//当左子树不为空的时候则继续调用自己
             }
             if(temp.right != null ) {
                 temp.right.val += temp.val;
                 hasPathSum(temp.right, sum);
             }
            
         }
        return flag;
    
        //以下是来自网友的另一种解法
         /*public boolean hasPathSum(TreeNode root, int sum) {
                if(root==null){
                    return false;         //我常犯的错误就是把递归里的返回值理解为是整体的返回,其实这只是递归的一步返回
                }
                if(root.left==null &&root.right==null){//当是叶子节点的时候
                    if(sum-root.val==0){
                        return true;  //如果满足结果则返回true
                    }else{
                        return false;  //否则就返回false
                    }
                }
                boolean left=hasPathSum(root.left,sum-root.val); //理解的重点,不断的递归
                boolean right=hasPathSum(root.right,sum-root.val);
                return left||right;//当左子树满足或者右子树满足都可以,当底层的树满.足会不断的返回,直到返回最上层,还是要深入理解递归的思路
            }*/
         
     }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值