leetcode_112_Path Sum
2015-03-26 20:16
471 查看
描述:
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->2which sum is 22.
思路:
由于是root-to-leaf,马上就想到了后序遍历,直接遍历到叶子节点,把从根节点到叶子节点的值统计一下看其和是否等于sum,相等的话则返回true,不等的话继续遍历直到下一个叶子节点。。。循环直至遍历结束。只是感觉,这么简单的一个题目,用后序遍历来解,杀鸡用牛刀?这感觉还挺不错!
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)
忽然感觉,这树的几种遍历方式可真的很有用。
代码:
像是把后序遍历的代码又粘了一遍。。。public boolean hasPathSum(TreeNode root, int sum){ int num=0; if (root == null) return false; Stack<TreeNode> st = new Stack<TreeNode>(); Stack<TreeNode> st1 = new Stack<TreeNode>(); st.push(root); num+=root.val; TreeNode top = null; while (!st.empty()) { top=st.peek(); while(top.left!=null)//达到页结点 { st.push(top.left); num+=top.left.val; top=top.left; } while(!st.empty()) { top=st.peek(); if(top.right==null)//无右子树时,访问结点 { if(top.left==null&&num==sum) return true; st.pop(); num-=top.val; }else { if(st1.empty()||(!st1.empty()&&st1.peek()!=top))//有右子树且第一次出现,将右子树入栈,并将结点在st1中标记一下 { st1.push(top); st.push(top.right); num+=top.right.val; break;//右子树入栈了,然后从右子树开始 } else//有右子树,但是第二次出现了,访问该结点 { st1.pop(); st.pop(); num-=top.val; } } } } return false; }
结果:
相关文章推荐
- [leetcode 112] Path Sum
- leetcode 112 —— Path Sum
- [Leetcode 11] 112 Path Sum
- Java [Leetcode 112]Path Sum
- <LeetCode><Easy> 112 Path Sum --二叉树深度优先遍历
- leetcode(112):Path Sum
- 【LEETCODE】112-Path Sum
- 【LeetCode从零单排】No112 Path Sum
- LeetCode 112 Path Sum
- LeetCode112——path sum
- Leetcode_112_Path Sum
- LeetCode(112)Path Sum
- leetcode_question_112 Path Sum
- Leetcode 112 Path Sum
- leetcode[112]Path Sum
- LeetCode112 Path Sum
- LeetCode笔记:112. Path Sum
- LeetCode 112: Path Sum
- <LeetCode OJ> 112/113. Path Sum(I / II)
- leetcode-112-Path Sum