本文是在学习中的总结,欢迎转载但请注明出处: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. 编程英语之KNN算法

    School of Computer Science The University of Adelaide   Artificial Intelligence Assignment 2   Semes ...

  2. Ubuntu 搭建 GlusterFS 过程笔记

    https://download.gluster.org/pub/gluster/ #要安装的东西 ---- ``` apt install -y build-essential gcc make c ...

  3. python if判断语句&计算

    python对缩进要求严格,代码块里的缩进必须一样,可以常用 tab键  表示4个空格 if 条件: 代码块 else: if判断语句如下: 1 print("吃饭,喝水,回家") ...

  4. Docker常见仓库MongoDB

    MongoDB 基本信息 MongoDB 是开源的 NoSQL 数据库实现. 该仓库提供了 MongoDB 2.2 ~ 2.7 各个版本的镜像. 使用方法 默认会在 27017 端口启动数据库. $ ...

  5. GC对象分配规则

    1.对象优先分配在Eden区,如果Eden区没有足够的空间时,虚拟机执行一次Minor GC. 2.大对象直接进入老年代(大对象是指需要大量连续内存空间的对象).这样做的目的是避免在Eden区和两个S ...

  6. 【Android】给Android Studio设置代理

    先打开我们的Android Studio,点击工具栏的file下的settings,如下图 之后再搜索框上面输入Proxy,然后按第四步提示点击,如下图 之后就进入了设置代理的界面了,如下图 默认情况 ...

  7. Dynamics CRM2016 Web API之通过实体的primary key查询记录

    CRM2016启用了webapi 而弃用了odata,作为码农的我们又开始学习新东西了. 下面是一段简单的查询代码,通过systemuser的primary key来查询一条记录 Web API查询方 ...

  8. Android的log日志知识点剖析

    log类的继承结构 Log public final class Log extends Object java.lang.Object ↳ android.util.Log log日志的常用方法 分 ...

  9. JAVA面向对象-----main方法详解

    JVM看不懂的可以跳过,这里不做过多解释,(^__^) 嘻嘻-- 主函数是静态的 public static void main(String[] args){ } 主函数是什么:主函数是一个特殊的函 ...

  10. Android Multimedia框架总结(一)MediaPlayer介绍之状态图及生命周期

    请尊重分享成果,转载请注明出处: http://blog.csdn.net/hejjunlin/article/details/52349221 前言:从本篇开始,将进入Multimedia框架,包含 ...