leetcode_112_Path Sum

来源:互联网 发布:阿房宫读音知乎 编辑:程序博客网 时间:2024/06/06 03:02

描述:

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.

思路:

由于是root-to-leaf,马上就想到了后序遍历,直接遍历到叶子节点,把从根节点到叶子节点的值统计一下看其和是否等于sum,相等的话则返回true,不等的话继续遍历直到下一个叶子节点。。。循环直至遍历结束。
只是感觉,这么简单的一个题目,用后序遍历来解,杀鸡用牛刀?这感觉还挺不错!大笑忽然感觉,这树的几种遍历方式可真的很有用。

代码:

像是把后序遍历的代码又粘了一遍。。。
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;    }

结果:


0 0
原创粉丝点击