码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Path Sum

时间:2014-09-10 01:35:19      阅读:221      评论:0      收藏:0      [点我收藏+]

标签: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 }

 

[LeetCode] Path Sum

标签:des   style   blog   color   io   ar   for   div   sp   

原文地址:http://www.cnblogs.com/yuhaos/p/3963630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!