問題:判斷二叉樹是否為平衡二叉樹
分析:樹上的任意結點的左右子樹高度差不超過1,則為平衡二叉樹。
搜索遞歸,記錄i結點的左子樹高度h1和右子樹高度h2,則i結點的高度為max(h1,h2)=1,|h1-h2|>1則不平衡
c++
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int flag=true;
int dfs(TreeNode *root)
{
if(root==NULL) return true;
int h1,h2;
if(root->left==NULL) h1=0;
else h1=dfs(root->left);
if(root->right==NULL) h2=0;
else h2=dfs(root->right);
if(abs(h1-h2)>1) flag=0;
return max(h1,h2)+1;
}
bool isBalanced(TreeNode *root) {
dfs(root);
return flag;
}
};
javascript:定義一個全局變量,記錄某個二叉樹是否平衡。
/**
* 題意:判斷二叉樹是否為平衡二叉樹
* 分析:枚舉節點判斷其左子樹的高度和右子樹的高度差是否小於1
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
flag = true;
if(root == null) return true;
var left = DFS(root.left);
var right = DFS(root.right);
if(Math.abs(left-right)>1) {
flag = false;
}
return flag;
};
flag = true;
function DFS(root){
if(root == null) return 0;
var left = DFS(root.left) +1;
var right = DFS(root.right) +1;
if(Math.abs(left-right)>1) {
flag = false;
}
return Math.max(left,right);
}
改進:若某個節點已經不平衡了,則直接返回高度為-1,如此便不用重新定義一個變量
/**
* 題意:判斷二叉樹是否為平衡二叉樹
* 分析:枚舉節點判斷其左子樹的高度和右子樹的高度差是否小於1
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
if(root == null) return true;
return DFS(root) != -1;
};
function DFS(root){
if(root == null) return 0;
var left = DFS(root.left);
var right = DFS(root.right);
if(left==-1 || right==-1 || Math.abs(left-right)>1) {//-1表示存在不平衡的情況
return -1;
}
return Math.max(left,right) + 1;
}
