题目要求

假设有一个二叉树,和一个目标值,如果存在一条从根节点到叶节点的路径,该路径上所有节点上的值的和恰好等于该目标值,则返回true,否则返回FALSE
方法的输入为根节点和目标值
例如:假设有一颗二叉树如下,目标值为22,结果返回true,因为存在一条路径5->4->11->2其和为22

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

思路一 : 递归

/**
 * @author rale
 *
 *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 and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
   return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
 */

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

思路二:循环(使用堆栈)

public class PathSum_112 {    
    public boolean hasPathSum2(TreeNode root, int sum) {
        Stack <TreeNode> stack = new Stack<> ();        
        stack.push(root) ;        
        while (!stack.isEmpty() && root != null){
            TreeNode cur = stack.pop() ;    
            if (cur.left == null && cur.right == null){                
                if (cur.val == sum ) return true ;
            }
            if (cur.right != null) {
                cur.right.val = cur.val + cur.right.val ;
                stack.push(cur.right) ;
            }
            if (cur.left != null) {
                cur.left.val = cur.val + cur.left.val;
                stack.push(cur.left);
            }
        }        
        return false ;
    }
    
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行