leetcode--Path Sum

来源:互联网 发布:手机视频点播软件 编辑:程序博客网 时间:2024/06/06 02:03

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.


分类:二叉树

题意:在二叉树中查找和为sum的路径(从根节点到叶子节点)


解法1:递归。由于sum可能是负数,所以必须遍历到根节点,过程中不能剪枝。

[java] view plain copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * public class TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode left; 
  6.  *     TreeNode right; 
  7.  *     TreeNode(int x) { val = x; } 
  8.  * } 
  9.  */  
  10. public class Solution {  
  11.     public boolean hasPathSum(TreeNode root, int sum) {  
  12.         if(root==nullreturn false;  
  13.         if(root.val==sum &&root.left==null&&root.right==null){  
  14.             return true;  
  15.         }else{  
  16.             return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val);  
  17.         }  
  18.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46379151