[C]LeetCode:Balanced Binary Tree

来源:互联网 发布:软件poc产品 编辑:程序博客网 时间:2024/06/06 16:32

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.

此题解法1:进行DFS递归算出两边长度,然后进行比较,依次进行上述比较的递归 得到结果

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */bool isBalanced(struct TreeNode* root) {    if (root==NULL)        return true;    int suml=depth(root->left);    int sumr=depth(root->right);    if(abs(suml-sumr)>1)        return false;    return (isBalanced(root->left)&&isBalanced(root->right));    }int depth(struct TreeNode* nodes){    if (nodes==NULL)        return 0;    int suml=depth(nodes->left);    int sumr=depth(nodes->right);    return suml>sumr?suml+1:sumr+1;}
0 0
原创粉丝点击