题解 | #单链表的排序#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
class Solution { public: bool IsBalanced_Solution(TreeNode* pRoot) { // 当树为空时,返回TRUE if(pRoot == nullptr) return true; int leftHeight = treeHeight(pRoot->left); int rightHeight = treeHeight(pRoot->right); if(abs(leftHeight - rightHeight) > 1) // 判断左右子树的差值是否大于一,大于一返回FALSE return false; // 最后当左子树和右子树都符合平衡二叉树时,返回TRUE return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); } int treeHeight(TreeNode* pRoot) { // 计算左右子树的层数 if(pRoot==nullptr) return 1; int leftHeight = treeHeight(pRoot->left); int rightHeight = treeHeight(pRoot->right); return max(leftHeight, rightHeight) + 1; } };