标签:style blog io ar color sp for on div
这道题也不是非常的难,弄楚平衡二叉树(AVL)的判断方法就行:
1.判断左子树高度与右子树高度之差是否小于1
2.判断根节点左子树是否满足平衡二叉
3.判断根节点右子树是否满足平衡二叉
满足以上三个条件才是AVL树
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode *root) { 13 if(root==NULL) return true; 14 if(root->left==NULL && root->right==NULL) return true; 15 if(abs(getHeight(root->left)-getHeight(root->right)) > 1) return false; 16 return isBalanced(root->left) && isBalanced(root->right); 17 } 18 int getHeight(TreeNode *node){ 19 if(node==NULL) return 0; 20 else 21 { 22 int i=getHeight(node->left); 23 int j=getHeight(node->right); 24 return i>j?i+1:j+1; 25 } 26 27 } 28 };
标签:style blog io ar color sp for on div
原文地址:http://www.cnblogs.com/suyuanhxx/p/4131132.html