[leetcode#110, 112, 113] Balanced Binary Tree, path sum, path sum II

Source: Internet
Author: User

Problem 1 [Balanced Binary Tree]

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

For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the 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 this adding up all the values along the Path equals the given sum.

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

              5             /             4   8           /   /           /  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 sum = 22 and,

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



The three problems is very easy to some extent, but they differ with each other, regarding the proper mechanism of Passi Ng answer set and arguments.

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

1. How do I 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 was a balance binary tree, we need to get the height of the left-sub tree and Right-sub tree. Can We do it on this?

int left_tree_height, ...)

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

Choice 1:record the height in a array (ArrayList), but we had only one height value to pass between and adjacent Recursi On levels. It seems to complex the problem.

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

My Solution:

 Public classSolution { Public Booleanisbalanced (TreeNode root) {if(Root = =NULL)//An empty tree            return true; if(Gettreeheight (root) = =-1)            return false; Else            return true; }        Private intgettreeheight (TreeNode cur_root) {if(Cur_root = =NULL)            return0; intLeft_height =gettreeheight (Cur_root.left); intRight_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; returnLeft_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 VA Lue.

My Solution:

 Public classSolution { Public BooleanHaspathsum (TreeNode root,intsum) {                if(Root = =NULL)            return false; returnHelper (root, sum); }        Private BooleanHelper (TreeNode Cur_root,intsub_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; }                returnHelper (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 a advanced version of PROBLEM3, it includes many skills we should master when writing an useful Recursio  N 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 is globally accessiable. This means on each recursion branches, it could be updated, and the effects are 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 is 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 is a disaster. Since Each recursion level has a 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 OT Her searching branches. <all we want to get and use are the information, not the list>

New Arraylist<integer> (ans); ArrayListNew arraylist<integer> (ans);

My Solution:

 Public classSolution { Public Booleanisbalanced (TreeNode root) {if(Root = =NULL)//An empty tree            return true; if(Gettreeheight (root) = =-1)            return false; Else            return true; }        Private intgettreeheight (TreeNode cur_root) {if(Cur_root = =NULL)            return0; intLeft_height =gettreeheight (Cur_root.left); intRight_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; returnLeft_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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.