首页 > 其他 > 详细

leetcode_112_Path Sum

时间:2015-03-26 20:52:29      阅读:186      评论:0      收藏:0      [点我收藏+]

描述:

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;
    }

结果:

技术分享

leetcode_112_Path Sum

原文:http://blog.csdn.net/mnmlist/article/details/44654673

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!