LeetCode OJ - Balanced Binary Tree

来源:互联网 发布:淘宝上的尼康典范店 编辑:程序博客网 时间:2024/06/06 11:43

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.

分析:由Maximum Depth of Binary Tree 题目改进, 自底向上

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    int ret;public:    bool isBalanced(TreeNode *root) {        if(root == NULL) return true;                ret = true;        DFS(root);                return ret;    }        int DFS(TreeNode *root) {        if(!ret) return 0;                if(!root->left && !root->right) {            return 1;        }                 int ldepth = 0;        int rdepth = 0;        if(root->left) {            ldepth = DFS(root->left);        }        if(root->right) {            rdepth = DFS(root->right);        }                if(ldepth != rdepth + 1 && ldepth != rdepth - 1 && ldepth != rdepth) {            ret = false;        }        return max(ldepth, rdepth) + 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 isBalanced(TreeNode *root) {        int dep = 0;        return check(root, dep);    }        bool check(TreeNode *root, int &dep) {        if(!root) {            dep = 0;            return true;        }                int leftDep, rightDep;        if(!check(root->left, leftDep)) return false;        if(!check(root->right, rightDep)) return false;                dep = max(leftDep, rightDep) + 1;        return abs(leftDep - rightDep) <= 1;    }};




0 0
原创粉丝点击