Balanced Binary Tree (LeetCode)

Question:

https://oj.leetcode.com/problems/balanced-binary-tree/

 

解答:

这道题有些被它的要求弄糊涂了。

"

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.

"

明明是height balanced,但是又定义成depth never differ by more than 1.

所以先要弄明白depth和height的区别:

From Wiki:

The height of a node is the length of the longest downward path to a leaf from that node. The height of the root is the height of the tree.

The depth of a node is the length of the path to its root (i.e., its root path). This is commonly needed in the manipulation of the various self-balancing trees, AVL Trees in particular.

The root node has depth zero, leaf nodes have height zero, and a tree with only a single node (hence both a root and leaf) has depth and height zero. Conventionally, an empty tree (tree with no nodes, if such are allowed) has depth and height −1.

 

Or:

    • The depth of a node is the number of edges from the node to the tree's root node.
      A root node will have a depth of 0.

    • The height of a node is the number of edges on the longest path from the node to a leaf.
      A leaf node will have a height of 0.

 

A tree, with height and depth of each node

 

所以我理解这道题的意思是指任意node,它的左右子树的height相差不超过1. 也就是说左子树根节点到最远叶节点的距离(edge数)跟右子树根节点到最远叶节点的距离差不大于1.

 

注意code里把NULL节点height设成0,这样就不用判断是否当前node是NULL的情况,叶节点的height为1.不影响结果但是code更加简单一些。

 

/**
 * 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 height = 0;
        return IsBalanced(root, height);
    }
    
    bool IsBalanced(TreeNode* node, int& height)
    {
        height = 0;
        if (!node)
            return true;

        int leftHeight = 0;
        if (!IsBalanced(node->left, leftHeight))
            return false;
            
        int rightHeight = 0;    
        if (!IsBalanced(node->right, rightHeight))
            return false;
            
        if (abs(leftHeight - rightHeight) > 1)
            return false;
            
        height = max(leftHeight, rightHeight) + 1;
        
        return true;
    }
};

 

posted @ 2014-10-16 13:33  smileheart  阅读(182)  评论(0)    收藏  举报