二叉樹的深度和平衡二叉樹

求平衡二叉樹二叉樹要用到二叉樹的深度,所以將這兩個算法放在一起。

首先來看球二叉樹的深度。

題目描述
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。

思路比較簡單,就是遞歸比較左右子樹的高度值,取較大的值。

//二叉數的數據結構
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

public int TreeDepth(TreeNode pRoot)
{
    if(pRoot == null) return 0;
    return Math.max(TreeDepth(pRoot.left)+1, TreeDepth(pRoot.right)+1);
}

接下來看看判斷一棵二叉樹是不是平衡二叉樹。

平衡二叉樹具有以下性質:它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。

//二叉數的數據結構
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

public boolean IsBalanced_Solution(TreeNode root) {
    if(root == null) return true;
    if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1)
        return false;
    return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}

public int getHeight(TreeNode pRoot)
{
    if(pRoot == null) return 0;
    return Math.max(getHeight(pRoot.left)+1, getHeight(pRoot.right)+1);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章