39、剑指offer--平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路:平衡二叉树,对于每个根节点左右子树高度差小于等于1
1 class Solution { 2 public: 3 int TreeDepth(TreeNode* pRoot) 4 { 5 if(pRoot == NULL) 6 return 0; 7 int nLeft = TreeDepth(pRoot->left); 8 int nRight = TreeDepth(pRoot->right); 9 10 return (nLeft > nRight)?(nLeft+1):(nRight+1); 11 } 12 bool IsBalanced_Solution(TreeNode* pRoot) { 13 if(pRoot == NULL) 14 { 15 return true; 16 } 17 int nLeft = TreeDepth(pRoot->left); 18 int nRight = TreeDepth(pRoot->right); 19 int diff = nLeft-nRight; 20 if(diff < -1 || diff > 1) 21 return false; 22 return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); 23 } 24 };