LeetCode-Path Sum

35 篇文章 0 订阅
22 篇文章 0 订阅

典型dfs,但是dfs写的太少了==

base case想了很久,main函数里面怎么处理第一次调用也想了很久。把判断条件搞错了好几次。应该在每次走到这个节点时就判断左右子是否为空。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if ( root == null )
            return false;
        boolean ans = false;
        if ( DFS(root,sum) )
            ans =  true;
        return ans;
    }
    
    public boolean DFS ( TreeNode node, int sum){
        if ( node.left == null && node.right == null && sum == node.val )
            return true;
            
        if ( node.left != null && DFS ( node.left, sum - node.val) == true )
            return true;
        else if ( node.right != null && DFS ( node.right, sum - node.val) == true)
            return true;
        else
            return false;
    }
    
    
    
    
}

下面是别人写的 比较清晰

一周多之后又来写了,看了一眼更好的答案:

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

iterative:

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
<span style="white-space:pre">	</span>if(root == null)
<span style="white-space:pre">		</span>return false;
     <span style="color:#ff6666;">   while ( !stack.isEmpty()){ </span>
            TreeNode cur = stack.pop();
            if ( cur.val == sum && cur.left == null && cur.right == null){
                return true;
            }
            if ( cur.left!= null){
                cur.left.val += cur.val;//注意一定先更新val再push
                stack.push(cur.left);
                
            }
            if ( cur.right != null){
                cur.right.val += cur.val;
                stack.push(cur.right);
            }
        }
        return false;
    } 
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值