110Balanced Binary Tree
问题:判断二叉树是否为平衡二叉树
分析:树上的任意结点的左右子树高度差不超过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; }