标签:des style blog color io ar for div sp
1 /** 2 * Definition for binary tree 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 int tmpSum=0; 13 Stack<TreeNode> nodeStack = new Stack<TreeNode>(); 14 TreeNode nowNode = root; 15 boolean popNode = false; 16 17 if (root==null) return false; 18 if (root.val==sum && root.left==null && root.right==null) return true; 19 20 while (!(nowNode==root && popNode)) { 21 if (!popNode) { 22 if (nowNode == null) { 23 popNode = true; 24 } else { 25 tmpSum += nowNode.val; 26 nodeStack.push(nowNode); 27 nowNode = nowNode.left; 28 } 29 } else { 30 if (nowNode == nodeStack.peek().right) { 31 if (nowNode==null && tmpSum==sum && nodeStack.peek().left==null) return true; 32 nowNode = nodeStack.pop(); 33 tmpSum -= nowNode.val; 34 } else { 35 nowNode = nodeStack.peek().right; 36 popNode = false; 37 } 38 } 39 } 40 return false; 41 } 42 }
标签:des style blog color io ar for div sp
原文地址:http://www.cnblogs.com/yuhaos/p/3963630.html