[Leetcode]Balanced Binary Tree

来源:互联网 发布:淘宝联盟赚钱吗? 编辑:程序博客网 时间:2024/06/07 01:26

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) {} * }; */


我的思路是要判断整棵树是否平衡,先判断每个节点是否平衡。要判断每个节点是否平衡,就要求每个节点的左右子树是否高度在1以内。

关于二叉树的各种递归函数,我一般都是设置为void型。如果要求某种性质(如高度)或者判断某种条件(如是否平衡),我都会用一个变量(的引用)记录。

class Solution {public:    bool isBalanced(TreeNode *root) {        bool balanced = true;        isTreeBalanced(root, balanced);        return balanced;    }    private:    void isTreeBalanced(TreeNode *root, bool& balancedSofar) {   //  判断整棵树是否平衡        if(root == NULL || !balancedSofar)            return;                if(!isNodeBalanced(root)) {            balancedSofar = false;            return;        }        isTreeBalanced(root->left, balancedSofar);        isTreeBalanced(root->right, balancedSofar);    }    bool isNodeBalanced(TreeNode *root) {   //  判断节点是否平衡        if(root == NULL)            return true;                    int leftTreeDepth = 0;        height(root->left, 1, leftTreeDepth);        int rightTreeDepth = 0;        height(root->right, 1, rightTreeDepth);                if(leftTreeDepth-rightTreeDepth > 1 || rightTreeDepth - leftTreeDepth > 1)            return false;        else            return true;    }void height(TreeNode *root, int currentDepth, int& maxD) {  //  求树的高度(根为1)if (root == NULL)return;if (root->left == NULL && root->right == NULL && currentDepth > maxD) {  //  叶节点maxD = currentDepth;return;}height(root->left, currentDepth + 1, maxD);height(root->right, currentDepth + 1, maxD);}};


                                             
0 0
原创粉丝点击