Problem 1 [Balanced Binary Tree]

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Problem 2 [Path Sum]

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

Problem 3 [Path Sum II]

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

The three problems  are very easy at some extent, but they differ with each other, regarding the proper mechanism of passing answer set and arguments.

The three problems include two very important issues in writing a recursion program.

1. How to pass the arguments to next level recursion?

2. How to return the answer set?

In problem1: (feedback to root level)

In order to test if a tree is a balance binary tree, we need to get the height of left-sub tree and right-sub tree.  Can we do it in this way ?

get_height(..., int left_tree_height, ...)

Absolutely no, Java pass arguments by value(the change in low-level recursion is just within its own scope).Thus we have to use other choices.

Choice 1: Record the height in an array(ArrayList), but we have only one height value to pass between two adjacent recursion levels. It seems to complex the problem.

Choice 2: Return height as a return value. It seems very reasonable, but how could we pass the vlidation information back(we check along the recursion path). We have already use height as return value, we can't return a boolean value at the same time.  There is a way to solve this problem: Since we pass height, and the height would never be a negative number, how about using "-1" to indicate invalidation.

My solution:

public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) //an empty tree
return true; if (getTreeHeight(root) == -1)
return false;
else
return true;
} private int getTreeHeight(TreeNode cur_root) { if (cur_root == null)
return 0; int left_height = getTreeHeight(cur_root.left);
int right_height = getTreeHeight(cur_root.right); if (left_height == -1 || right_height == -1) //the -1 represent violation happens in the sub-tree
return -1; if (Math.abs(left_height - right_height) > 1) //the violation happens in the current tree
return -1; return left_height > right_height ? left_height + 1 : right_height + 1;
//return the new height to the pre level recursion
}
}

In problem 2: (feedback to root level)

Since we just care about whether there exists an path equal to the sum, we could directly use a boolean value as return value.

My solution:

public class Solution {
public boolean hasPathSum(TreeNode root, int sum) { if (root == null)
return false; return helper(root, sum);
} private boolean helper(TreeNode cur_root, int sub_sum) { if (cur_root == null)
return false; if (cur_root.left == null && cur_root.right == null) { //reach the leaf node
if (cur_root.val == sub_sum)
return true;
} return helper(cur_root.left, sub_sum - cur_root.val) || helper(cur_root.right, sub_sum - cur_root.val);
}
}

In problem 3:(no need to feed back to root level, directly add answer to result set at base level)

This problem is an advanced version of problem3,  it includes many skills we should master when writing an useful recursion program.  We should first note following facts:

1. we need a global answer set, thus once we have searched out a solution, we could directly add the solution into the answer set. The effects scope of this set should be globally accessiable. This means at each recursion branches, it could be updated, and the effects is in global scope. We pass it as an argument.

public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {

        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>> ();
if (root == null)
return ret; ArrayList<Integer> ans = new ArrayList<Integer> ();
helper(root, sum, ans ,ret); return ret;
}

2. We should keep the path's previous information before reaching the current node. We should be able to mainpulate on the information, and pass it to next recursion level. The big problem comes out : if we manipulate on the same object(list), this could be a disaster. Since each recursion level has two sparate searching branches.

The solution: we make a copy of passed in list, thus we can use the information recorded in the list, without affecting other searching branches. <All we want to get and use is the information, not the list>

 ArrayList<Integer> left_ans_copy = new ArrayList<Integer> (ans);
ArrayList<Integer> right_ans_copy = new ArrayList<Integer> (ans);

My solution:

public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) //an empty tree
return true; if (getTreeHeight(root) == -1)
return false;
else
return true;
} private int getTreeHeight(TreeNode cur_root) { if (cur_root == null)
return 0; int left_height = getTreeHeight(cur_root.left);
int right_height = getTreeHeight(cur_root.right); if (left_height == -1 || right_height == -1) //the -1 represent violation happens in the sub-tree
return -1; if (Math.abs(left_height - right_height) > 1) //the violation happens in the current tree
return -1; return left_height > right_height ? left_height + 1 : right_height + 1;
//return the new height to the pre level recursion
}
}

[LeetCode#110, 112, 113]Balanced Binary Tree, Path Sum, Path Sum II的更多相关文章

  1. LeetCode之“树”:Balanced Binary Tree

    题目链接 题目要求: Given a binary tree, determine if it is height-balanced. For this problem, a height-balan ...

  2. LeetCode(24)-Balanced Binary Tree

    题目: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced bin ...

  3. C++版 - 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解

    剑指offer 面试题39:判断平衡二叉树 提交网址:  http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId= ...

  4. LeetCode 110. 平衡二叉树(Balanced Binary Tree) 15

    110. 平衡二叉树 110. Balanced Binary Tree 题目描述 给定一个二叉树,判断它是否是高度平衡的二叉树. 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点的左右两个子树 ...

  5. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  6. 110.Balanced Binary Tree Leetcode解题笔记

    110.Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, ...

  7. 110. Balanced Binary Tree - LeetCode

    Question 110. Balanced Binary Tree Solution 题目大意:判断一个二叉树是不是平衡二叉树 思路:定义个boolean来记录每个子节点是否平衡 Java实现: p ...

  8. Leetcode 110 Balanced Binary Tree 二叉树

    判断一棵树是否是平衡树,即左右子树的深度相差不超过1. 我们可以回顾下depth函数其实是Leetcode 104 Maximum Depth of Binary Tree 二叉树 /** * Def ...

  9. [LeetCode] 110. Balanced Binary Tree ☆(二叉树是否平衡)

    Balanced Binary Tree [数据结构和算法]全面剖析树的各类遍历方法 描述 解析 递归分别判断每个节点的左右子树 该题是Easy的原因是该题可以很容易的想到时间复杂度为O(n^2)的方 ...

随机推荐

  1. css考核点整理(一)-浮动的理解和清除浮动的几种方式

    浮动的理解和清除浮动的几种方式 clear语法:clear : none | left | right | both 取值:none : 默认值.允许两边都可以有浮动对象left : 不允许左边有浮动 ...

  2. css 权威指南笔记( 五)结构和层叠之三种样式来源

    CSS中的样式一共有三种来源:创作人员.读者和用户代理,来源的不同会影响到样式的层叠方式 首先,创作人员(author's+style)样式应该是我们最熟悉的,如果你是一个前端开发者,那么你写的那些样 ...

  3. 自己做的萌萌哒的js宠物挂件~

    OwO萌物v1.1 类似wp伪春菜,但纯js不用后端,且可定制程度非常高~,3个人格示例,需要的童鞋自提 仙六 - 越祈 作者:正逍遥0716 2016/5/15 CLANNAD - 藤林杏 作者:正 ...

  4. rabbitMQ实战(一)---------使用pika库实现hello world

    rabbitMQ实战(一)---------使用pika库实现hello world 2016-05-18 23:29 本站整理 浏览(267)     pika是RabbitMQ团队编写的官方Pyt ...

  5. order by

  6. 在往oracle中插数据时,如何处理excel读取的时间空值

    //若从excel中读取的时间值为空值时,做如下转换 string YDKGSJ = string.Empty; if (dbdata.Rows[i]["约定开工时间"].ToSt ...

  7. 嵌入式css样式,写在当前的文件中

    现在有一任务,把下面的“超酷的互联网”.“服务及时贴心”.“有趣易学”这三个短词文字字号修改为18px. 如果用内联式css样式的方法进行设置将是一件很头疼的事情(为每一个<span>标签 ...

  8. 关于JavaScript的类的继承

    其实最一开始学JS的时候就看过继承的实现.当时只是去试着理解从书上看来的代码段而已.今天又重新思考了一下,感觉这是一个思维探索演进的结果. 继承,即复用. 如果抛开继承的固有思想,让b复用a的成员,最 ...

  9. mysql 数据sqoop到hive 步骤

    1.hive建表 hive是支持分区的,但是这次建表没有写分区. CREATE TABLE `cuoti_rpt` ( `COURSE_ID` string, `NAME` string, `PERI ...

  10. SGU 145.Strange People(无环K短路)

    时间:0.25s空间:4m 题意: 其实就是求无环第K短路. 输入: 给出n,m,k,分别代表,n个点,m条边,第k长路. 接下来m行,三个整数x,y,z,分别代表x,y之间有条费用为x的双向路.保证 ...