劍指Offer - 平衡二叉樹
阿新 • • 發佈:2018-02-14
log public oot com int 技術 pos item span
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。代碼
class Solution { bool isBalance(TreeNode* pRoot, int &h) { if (!pRoot) { h= 0; return true; } int lh, rh; if (!isBalance(pRoot->left, lh) || !isBalance(pRoot->right, rh)) return false; if (lh > rh + 1 || rh > lh + 1) return false; h = lh > rh ? lh + 1 : rh + 1; return true; } public: bool IsBalanced_Solution(TreeNode* pRoot) { int h = 0; return isBalance(pRoot, h); } };
劍指Offer - 平衡二叉樹