Balanced Binary Tree
Q:
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.
A:
递归求高度,不知道非递归怎么搞,遗憾。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { int length = 0; return isBalancedInternal(root, &length); } private: bool isBalancedInternal(TreeNode* root, int* length) { if (!root) { *length = 0; return true; } int l_len, r_len; if (!isBalancedInternal(root->left, &l_len) || !isBalancedInternal(root->right, &r_len) || abs(l_len - r_len) > 1) { return false; } *length = max(l_len, r_len) + 1; return true; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号