Leetcode 树 Balanced Binary Tree

来源:互联网 发布:ubuntu搭建hadoop集群 编辑:程序博客网 时间:2024/06/07 10:21

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie



Balanced Binary Tree

 Total Accepted: 13700 Total Submissions: 42780

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
思路:bfs递归
1.如果根节点的左右子树深度之差大于1,返回false
2.如果左子树或右子树不是平衡的,返回false
3.返回true
复杂度:时间O(n), 空间O(log n)

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


0 0
原创粉丝点击