110. Balanced Binary Treenode
Given a binary tree, determine if it is height-balanced.ide
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.函數
題目大意:
this
判斷一顆二叉樹是否爲平衡二叉樹。spa
思路:orm
作一個輔助函數來求的樹的高度。遞歸
經過輔助函數來遞歸求解。ci
代碼以下:it
/** * 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:26io