Wednesday, July 22, 2015

Leetcode 110: 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.

从下往上传值的tree recursion 问题
tree recursion一般可以由2种recursion 来解决问题, 一种是这题里面的pass value from down to top ,
// 1. what current node want from its children
//2. what current node do in current level
//3. what current node return to its parent.
另一种是 pass value from up to down, 这种一般都是要求从root 开始出发的, 就是基本的DFS的思想。

class Solution {
private:
    int getHeight(TreeNode* root, bool &rst) {
          //base case
        if (root == NULL) return 0;
        //what current node want from children
        int left = getHeight(root->left,rst);
        int right = getHeight(root->right, rst);
        //what current node do in current level
        if (abs(right-left) > 1) {
            rst &= false;
            return -1;
        }
        //what current node return to its parent
        return max(right, left) + 1;
    }
public:
    bool isBalanced(TreeNode* root) {
        bool rst = true;
        int tmp = getHeight(root, rst);
        if (tmp == -1) return false;
        return rst;
    }
};

No comments:

Post a Comment