本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41910495

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.

思路:

(1)题意为给定一个(每个节点带有数值)二叉树和一个整数,判断在二叉树中是否存在从树根到叶子节点路径使得路径之和等于给定的整数。

(2)我觉得该题主要考察对常用数据结构"栈"的熟悉和使用。包括栈的主要特性:先进后出、栈的peek()方法、栈的pop()方法、栈的push()方法。

(3)首先,通过分析可知,要想获取从树根到叶子节点的路径,必须对树进行遍历,本文应该按照:根—>左—>右的方式进行遍历。

(4)其次,需要考虑的是当我们遍历到叶子节点时,当路径值之和不等于给定值时,如何继续进行下去。

(5)再次,本文采用栈来存储路径上的节点,因为当遍历到叶子节点时,路径上节点值之和不等于给定值时只需将该叶子节点移除。首先,对根节点判空,如果为空返回null,如果只有一个根节点也需要进行特殊判断;然后,如果根节点不为空,将根节点压入栈中(为了让整棵树节点都可能被遍历到,只要栈中有元素就循环),并用临时变量count保存存入栈中节点的值,如果栈不为空就循环,取出栈顶元素,如果该元素有左孩子,就将左孩子压入栈中,并将值加到count中;如果该元素有右孩子,就将右孩子压入栈中,并将值加入count中;如果该元素没有左右孩子,且该元素不是树根,且count值和给定值相同,则返回true,否则将该元素从栈中移除,并从count中减去对应的值。

(6)在(5)中有一点在此处列出,需要特别注意:我们必须将每次从栈中弹出的节点保存在一个临时的Set中,并且在将节点的左右孩子存入栈中对其左右孩子是否在Set中进行判定,这样才能保证每个节点只进入栈一次,否则就会产生死循环。

(7)注:其中栈的peek()方法是取出栈顶元素,而不从栈中移除;栈的pop()方法是取出栈顶元素,并将其从栈中移除;栈的push()方法是将元素压入栈中;HashSet的contains()方法能够快速地判断某一元素是否在该Set中。

(8)这道题注意以上几个方面就能很容易得到正确答案。这道题其实不难,主要考察对数据结构中栈的使用,另外也对分析问题能力的考察。

(9)希望本文对你有所帮助。谢谢。

算法代码实现如下:

public static boolean hasPathSum(TreeNode root, int sum) {
	if (root == null)
		return false;
	if (root != null && root.left == null && root.right == null && root.val == sum)
		return true;
	//每个元素只能进栈一次
	Stack<TreeNode> stack = new Stack<TreeNode>();
	//保证元素值只进栈一次
	Set<TreeNode> set = new HashSet<TreeNode>();
	int count = 0;
	stack.push(root);
	count += root.val;
	while (stack.size() != 0) {
		TreeNode top = stack.peek();
		if (top.left != null && !set.contains(top.left)) {
			stack.push(top.left);
			count += top.left.val;
		} else if (top.right != null && !set.contains(top.right)) {
			stack.push(top.right);
			count += top.right.val;
		} else {
			if (top != root && top.left==null && top.right==null && count == sum) {
				return true;
			} else {
				TreeNode pop = stack.pop();
				set.add(pop);
				count = count - pop.val;
			}
		}
	}
	return false;
}

Leetcode_112_Path Sum的更多相关文章

  1. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  2. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  3. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  4. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  5. BZOJ 3944 Sum

    题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [LeetCode] Partition Equal Subset Sum 相同子集和分割

    Given a non-empty array containing only positive integers, find if the array can be partitioned into ...

  8. [LeetCode] Split Array Largest Sum 分割数组的最大值

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  9. [LeetCode] Sum of Left Leaves 左子叶之和

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

随机推荐

  1. vmware 12中安装MAC OS X Lion 10.7

    下载并安装vmware.    下载并安装MAC补丁.    创建虚拟机.    设置ISO文件.    开启虚拟机.    安装vmware tools. 1. 下载并安装vmware.我是直接在腾 ...

  2. Latex:TexStudio的使用

    http://blog.csdn.net/pipisorry/article/details/54565608 Texsdudio 快捷键 The keyboard shortcuts can be ...

  3. SQL_CALC_FOUND_ROWS equivalent in PostgreSQL

    https://www.postgresql.org/message-id/1185863074.10580.91.camel%40linda.lfix.co.uk On Tue, 2007-07-3 ...

  4. Programming In Scala笔记-第九章、控制抽象

    本章主要讲解在Scala中如何使用函数值来自定义新的控制结构,并且介绍Curring和By-name参数的概念. 一.减少重复代码 1.重复代码的场景描述 前面定义的函数,将实现某功能的代码封装到一起 ...

  5. Swift运行时简介

    因为Swift的操作在高层并且也得与Objc联合起来干活,用Swift写的程序一般会被Objc和Swift运行时处理.因为Swift的本性--换句话说,它是一门静态语言--Swift运行时在一些关键地 ...

  6. python命令行参数解析模块argparse和docopt

    http://blog.csdn.net/pipisorry/article/details/53046471 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的o ...

  7. ERROR: In <declare-styleable> MenuView, unable to find attribute android:preserveIconSpacing

    eclipse  sdk从低版本切换到高版本sdk的时候   v7包会包这个错ERROR: In <declare-styleable> MenuView, unable to find ...

  8. Android判断当前系统语言

    Android获取当前系统语言 getResources().getConfiguration().locale.getCountry() 国际化常用语言 中文: getResources().get ...

  9. SSH网上商城---用户激活

    在前面的博客中,小编主要结合SSH网上商城这个项目,简单的介绍了如何实现邮件发送的这个功能,邮件发送了,接下来就是激活了,为什么呢?现在大多网站都要通过对账号进行激活,然后才能注册成功,这是防止恶性注 ...

  10. 如何查看App provision profile文件中的钥匙链访问组名称

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 我们因为某些原因希望安全的在多个App中共享一些信息,我们可以 ...