劍指Offer-38.平衡二叉樹(C++/Java)

題目:

輸入一棵二叉樹,判斷該二叉樹是不是平衡二叉樹。spa

分析:

能夠從根節點開始遍歷每個節點,求得節點左右子樹的最大高度,判斷是否是平衡二叉樹。這樣作的問題在於會重複遍歷節點,形成沒必要要的浪費。code

因此能夠採用後續遍從來求解此題,判斷子樹是不是平衡二叉樹,若是是,就返回子樹的最大高度,不是的話,就停止遍歷,這樣作的話每一個節點只訪問一遍。blog

程序:

C++get

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(getHeight(pRoot) == -1)
            return false;
        return true;
    }
    int getHeight(TreeNode* root){
        if(root == nullptr)
            return 0;
        int leftHeight = getHeight(root->left);
        if(leftHeight == -1)
            return -1;
        int rightHeight = getHeight(root->right);
        if(rightHeight == -1)
            return -1;
        return abs(leftHeight - rightHeight) <= 1 ? 1 + max(leftHeight, rightHeight): -1;  
    }
};

Javaio

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(getHeight(root) == -1)
            return false;
        return true;
    }
    public int getHeight(TreeNode root){
        if(root == null)
            return 0;
        int leftHeight = getHeight(root->left);
        if(leftHeight == -1)
            return -1;
        int rightHeight = getHeight(root->right);
        if(rightHeight == -1)
            return -1;
        return Math.abs(leftHeight - rightHeight) <= 1 ? 1 + Math.max(leftHeight, rightHeight): -1;  
    }
}
相關文章
相關標籤/搜索