Tree_Graph determine whether to balance the binary tree @ CareerCup

Source: Internet
Author: User
ImplementafunctiontocheckifabinarytreeisbalancedForthepurposesofthisquestion, abalancedtreeisdefinedtobeatreesuchthattheheightsof

Implement a function to check if a binary tree is balanced. for the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.


A balanced binary tree is defined as an empty tree or its left and right subtrees. the absolute value of the height difference cannot exceed 1, and both left and right subtrees are a balanced binary tree.


Ideas:

1) first write a recursive tree height function, and then check whether the height difference of the subtree is greater than 1.

2) optimization: put the logic of checking whether the height difference of the subtree is greater than 1 in a recursive function that calculates the height of the tree, and return the result in time when an imbalance is encountered.


Note:

This question is different from asking whether a tree is balanced (the distance between any two leaf nodes of the tree and the root node is not greater than 1 ):


VcD4KPHA + PGJyPgo8L3A + Release/release/ydLUx/PK97XE1 + Release/release + 2yL/Jss6/release + CjwvcD4KPHA + Release/release + 2yKOsyLu687/JtcOhozwv CD4KPHA + ss6/fingerprint + PGJyPgo8L3A + CjxwPs/Cw + bKx8XQts/kx7fxxr1_rb + fill = "brush: java;"> package Tree_Graph; import CtCILibrary. assortedMethods; import CtCILibrary. treeNode; public class S4_1 {// recursive decision tree balance binary tree // Time: O (N ^ 2) public static boolean isBalanced (TreeNode root) {if (root = null) {return true;} int heightDiff = GetHeight (root. left)-getHeight (root. right); if (Math. abs (heightDiff)> 1) {// unbalanced return false;} else {return isBalanced (root. left) & isBalanced (root. right) ;}}// recursively retrieve the height of the tree public static int getHeight (TreeNode root) {if (root = null) {return 0 ;} return Math. max (getHeight (root. left), getHeight (root. right) + 1 ;} // ==================================== Improved version optimized version // put the logic for determining whether to balance in the checkHeight function, edge calculation height ,// Determines whether the edge is balanced. if it is not balanced,-1 // Time: O (N), Space: O (H), H: height of treepublic static boolean isBalanced2 (TreeNode root) is directly returned) {if (checkHeight (root) =-1) {return false;} else {return true ;}} // calculate the edge height and determine whether to balance public static int checkHeight (TreeNode root) {if (root = null) {return 0;} int leftHeight = checkHeight (root. left); if (leftHeight =-1) {return-1;} int rightHeight = checkHeight (root. right); if (rightHei Ght =-1) {return-1;} int heightDiff = leftHeight-rightHeight; if (Math. abs (heightDiff)> 1) {return-1;} return Math. max (leftHeight, rightHeight) + 1;} public static void main (String [] args) {// Create balanced treeint [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TreeNode root = TreeNode. createMinimalBST (array); System. out. println ("Root? "+ Root. data); System. out. println (" Is balanced? "+ IsBalanced (root); // cocould be balanced, actually, but it's very unlikely... treeNode unbalanced = new TreeNode (10); for (int I = 0; I <10; I ++) {unbalanced. insertInOrder (AssortedMethods. randomIntInRange (0,100);} System. out. println ("Root? "+ Unbalanced. data); System. out. println (" Is balanced? "+ IsBalanced (unbalanced ));}}



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.