Determine if a binary tree is a binary balance tree.
Links: https://oj.leetcode.com/problems/balanced-binary-tree/
Title Description:
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 subtrees of the Y node never differ by more than 1.
Give a binary tree and judge whether it is a balanced binary tree.
A balanced binary tree is defined with a two subtree height difference of not more than 1 per node.
This problem is relatively simple,
A tree is not a balanced binary tree, you can enter a node, calculate its two subtrees tree height difference, and then compare with 1, recursive this operation can complete the decision.
Recalling the concept of a binary tree, the balanced binary tree is based on a binary search tree (binary search trees),
Binary search tree or an empty tree;
Or a two-fork tree with the following properties:
(1) The Joz tree is not empty, then the value of all nodes on the left subtree is less than the value of its root node;
(2) If the right subtree is not empty, the value of all nodes on the right subtree is greater than the value of its root node;
(3) The left and right sub-trees are also two-fork sorting trees respectively;
Binary find tree is insert, sort, find the average time complexity is O (Log (n)), the worst case is O (n),
The balance factor of the binary tree is the depth of the left subtree of the node minus the depth of its right subtree, and the BF factor of the balanced binary tree is absolutely 1.
Following the completion of solution in Java, note the situation of empty trees:
Public classbalancedbinarytreesolution {/*** Access to local inner classes must have an outer class object, which must be decorated with static*///Public Static class TreeNode {//int val;//TreeNode left;//TreeNode right;//TreeNode (int x) {val = x;}// } //OJ support for JDK math functions Public Booleanisbalanced (TreeNode root) {//Notice the situation of the empty tree if(Root = =NULL) return true; intLeftdepth=getdepth (Root.left); intRightdepth=getdepth (root.right); intaltitude=rightdepth-leftdepth; //Note that there is only one vertex condition if(Math.Abs (altitude) >1) return false; Else //Recursive comparison returnisbalanced (Root.left) &&isbalanced (root.right); } Private intgetdepth (TreeNode node) {if(node = =NULL) return0; //Recursive seeking depth return1 +Math.max (Getdepth (Node.left), getdepth (Node.right)); }}
Leetcode: Balanced Binary Tree