leetcode 之 Balanced Binary Tree

来源:互联网 发布:防沉迷解除软件2016 编辑:程序博客网 时间:2024/05/23 12:59

问题:

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,利用DFS可以知道树的高度。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int height(TreeNode *node) {        if(node == NULL)            return 0;        //leaf        if(node->left == NULL && node->right == NULL)            return 1;        //non-leaf        return max(height(node->left), height(node->right)) + 1;    }    bool isBalanced(TreeNode *root) {        if(root == NULL)            return true;        int depth = abs(height(root->left) - height(root->right));        if(depth < 2)            return (isBalanced(root->left) && isBalanced(root->right));        else            return false;    }};



0 0
原创粉丝点击