Balanced Binary Tree

来源:互联网 发布:淘宝客购物车结算 编辑:程序博客网 时间:2024/06/05 04:08

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.

/** * 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  bRes;int depth(TreeNode* root){if (0 == root) return 0;if (0 == root->left && 0 == root->right)return 1;int depthL = depth(root->left);int depthR = depth(root->right);if (abs(depthL - depthR) > 1)bRes = false;return depthL > depthR ? 1 + depthL : 1 + depthR;}    bool isBalanced(TreeNode *root){bRes = true;depth(root);return bRes;            }}; 

说点自己的感觉,一开始做这道题稍微有点想法就忙去写代码,导致提交三次都错误,后来搞明白自己一直没有一个确定的思路,然后做完另一道题后,具体扎扎实实的总结了这道题,应该用什么思路,算法,结果得出,在递归求depth过程中,比较左右子树depth之差。

0 0