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.
Test Instructions: determines whether a given two-fork tree is a balanced binary tree.
idea: The recursive method is used to determine whether the depth of the left sub-tree and the depth of the right subtree are greater than 1, in which the function of seeking depth is written.
Code:
Public classSolution { Public Booleanisbalanced (TreeNode root) {if(root==NULL) return true; if(root.left==NULL&&root.right==NULL) return true; if(Math.Abs (Depth (root.left)-depth (root.right)) >1){ return false; } returnisbalanced (Root.left) &&isbalanced (root.right); } Public intdepth (TreeNode root) {if(root==NULL){ return0; } return1 +Math.max (Depth (root.left), Depth (root.right)); }}
Leetcode: Balanced Binary Tree