https://oj.leetcode.com/problems/path-sum/
实际上可看做二叉树的遍历。
只不过要比二叉树的遍历多存储一个变量,就是根节点到当前节点的和。
可以深度遍历也可广度遍历
深度遍历(前序遍历)
/**
* 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;
Stack<TreeNode>stack=new Stack<TreeNode>();
Stack<Integer>number=new Stack<Integer>();
stack.push(root);
number.push(root.val);
while(!stack.isEmpty()){
TreeNode temp=stack.pop();
int current=number.pop();
if(temp.right==null&&temp.left==null){
if(current==sum)return true;
}
if(temp.right!=null){
stack.push(temp.right);
number.push(temp.right.val+current);
}
if(temp.left!=null){
stack.push(temp.left);
number.push(temp.left.val+current);
}
}//while
return false;
}
}
广度遍历(层次遍历)
在java中LIinkedList可做queue使用
/**
* 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;
LinkedList<TreeNode>list=new LinkedList<TreeNode>();
LinkedList<Integer>number=new LinkedList<Integer>();
list.offer(root);
number.offer(root.val);
int ret=0;
while(!list.isEmpty()){
TreeNode temp=list.poll();
int cur=number.poll();
if(temp.left==null&&temp.right==null){
if(cur==sum)return true;
}
if(temp.left!=null){
list.offer(temp.left);
number.offer(temp.left.val+cur);
}
if(temp.right!=null){
list.offer(temp.right);
number.offer(temp.right.val+cur);
}
}
return false;
}
}
下面是一个递归算法
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)return false;
sum-=root.val;
if(root.left==null&&root.right==null)return sum==0;
return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
}
}