leetcode[110] Balanced 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 {

public:

    int heightTree(TreeNode *root)

    {

        if (!root) return 0;

        int lf = 0, ri = 0;

        if (root -> left)

            lf = heightTree(root -> left);

        if (root -> right)

            ri = heightTree(root -> right);

        return max(lf, ri) + 1;

    }

    

    bool isBalanced(TreeNode *root) {

        if (!root) return true;

        bool lf, ri;

        lf = isBalanced(root -> left);

        ri = isBalanced(root -> right);

        return lf && ri && (abs(heightTree(root->left)-heightTree(root->right))<=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:

    int heightTree(TreeNode *root)

    {

        if (!root) return 0;

        int lf = 0, ri = 0;

        if (root -> left)

            lf = heightTree(root -> left);

        if (root -> right)

            ri = heightTree(root -> right);

        return max(lf, ri) + 1;

    }

    

    bool isBalanced(TreeNode *root) {

        if (!root) return true;

        

        stack<TreeNode *> sta;

        TreeNode *p = root;

        

        while(p || !sta.empty())

        {

            while(p)

            {

                sta.push(p);

                p = p -> left;

            }

            if (!sta.empty())

            {

                p = sta.top();

                sta.pop();

                if (abs(heightTree(p -> left) - heightTree(p -> right)) > 1)

                    return false;

                p = p -> right;

            }

        }

        return true;

    }

};

 

你可能感兴趣的:(LeetCode)