您好,登錄后才能下訂單哦!
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
題目大意:
判斷一顆二叉樹是否為平衡二叉樹。
思路:
做一個(gè)輔助函數(shù)來求的樹的高度。
通過輔助函數(shù)來遞歸求解。
代碼如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int depth(TreeNode* root) { if(!root) return 0; int l = depth(root->left) ; int r = depth(root->right) ; return 1 + ((l > r)?l:r); } bool isBalanced(TreeNode* root) { if(!root) return true; else { int l = depth(root->left); int r = depth(root->right); if(l + 1 < r || r + 1 <l) { return false; } else return (isBalanced(root->left) && isBalanced(root->right) ); } } };
2016-08-08 00:25:26
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。