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.
思想:递归
- public int height(TreeNode root) {
- if(root==null) return 0;
- if(root.left == null && root.right == null) return 1;
- return Math.max(height(root.left),height(root.right))+1;
- }
- public boolean isBalanced(TreeNode root) {
- if(root==null) return true;
- if(root.left == null && root.right == null) return true;
- if(isBalanced(root.right) == false || isBalanced(root.left) == false) {
- return false;
- }
- if(Math.abs(height(root.left) - height(root.right))<=1) {
- return true;
- } else {
- return false;
- }
- }
改进:仅遍历一次节点
- bool isBalanced(TreeNode *root,int &height) {
- if(root==NULL) {
- height = 0;
- return true;
- }
- int left = 0;
- int lflag = isBalanced(root->left,left);
- int right = 0;
- int rflag = isBalanced(root->right,right);
- if(lflag&&rflag) {
- if(abs(left-right)<=1) {
- height = max(left,right) + 1;
- return true;
- }
- return false;
- }
- return false;
- }
- bool isBalanced(TreeNode *root) {
- int height=0;
- return isBalanced(root,height);
- }