1. 程式人生 > >[Leetcode] Balanced Binary Tree

[Leetcode] Balanced Binary Tree

ever 訪問 true 叠代 find this ref 計算 sub

Balanced Binary Tree 題解

題目來源:https://leetcode.com/problems/balanced-binary-tree/description/


Description

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.

Example

Example 1:

Given the following tree [3,9,20,null,null,15,7]:


    3
   /   9  20
    /     15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:


       1
      /      2   2
    /    3   3
  /  4   4

Return false.

Solution

class Solution {
private:
    int getHeight(TreeNode *node) {
        if
(!node) return 0; int lh, rh; lh = getHeight(node -> left); if (lh == -1) return -1; rh = getHeight(node -> right); if (rh == -1) return -1; int hDiff = lh - rh; if (hDiff <= 1 && hDiff >= -1
) return 1 + max(lh, rh); else return -1; } public: bool isBalanced(TreeNode* root) { if (!root) return true; return getHeight(root) != -1; } };

解題描述

這道題題意是判斷一棵二叉樹是不是平衡二叉樹,思路在於自底向上判斷節點是不是滿足平衡條件,如果滿足的話需要向上層遞交下層樹的高度。原先的想法是將判斷下方樹是不是滿足條件和計算下方樹高度分開成2個函數,但是這樣明顯時間復雜度較高,並且重復訪問了下方節點。於是後面思考了以下,可以將兩者二合一,如果下方子樹不平衡,其返回的樹高就是-1。這樣基於後續遍歷來遞歸計算樹高就可以判斷整棵樹的平衡性。

不過這道題也可以采用叠代的方式來做,采用棧來模擬遞歸即可:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root)
            return true;
        stack<TreeNode*> nodeStack;
        unordered_map<TreeNode*, int> heightMap; //節點與節點高度map
        nodeStack.push(root);
        while (!nodeStack.empty()) {
            TreeNode *node = nodeStack.top();
            nodeStack.pop();
            if (node -> left == NULL && node -> right == NULL) {
                // 葉子節點,高度為1
                heightMap[node] = 1;
            } else if (node -> left && 
                heightMap.find(node -> left) == heightMap.end()) {
                // 左子樹非空時,且左子樹高度未知時壓棧進行計算
                nodeStack.push(node);
                nodeStack.push(node -> left);
            } else if (node -> right && 
                heightMap.find(node -> right) == heightMap.end()) {
                // 右子樹同理
                nodeStack.push(node);
                nodeStack.push(node -> right);
            } else {
                // 獲取左右子樹樹高
                int lh = (node -> left) ? heightMap[node -> left] : 0;
                int rh = (node -> right) ? heightMap[node -> right] : 0;
                int hDiff = lh - rh;
                // 如果子樹上已經不平衡,說明整棵樹不是平衡二叉樹
                if (hDiff > 1 || hDiff < -1)
                    return false;
                heightMap[node] = 1 + max(lh, rh);
            }
        }
        return true;
    }
};

[Leetcode] Balanced Binary Tree