輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹(Java版)/輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。(Java版)

輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹(Java版)

package Day45;

/**
 * @Author Zhongger
 * @Description 輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹
 * @Date 2020.3.18
 */
public class AVLSolutionClass {
    private boolean flag=false;
    public static void main(String[] args) {

    }
    public boolean IsBalanced_Solution(TreeNode root){
        getDepth(root);
        return flag;
    }
    public int getDepth(TreeNode root){
        if (root==null){
            flag=true;
            return 0;
        }
        int leftDepth=getDepth(root.left);
        int rightDepth=getDepth(root.right);
        int depth=(leftDepth>rightDepth?leftDepth:rightDepth)+1;
        if (Math.abs(leftDepth-rightDepth)>1){
            flag=false;
        }else {
            flag=true;
        }
        return depth;
    }

}
class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }

}

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

package Day45;

/**
 * @Author Zhongger
 * @Description 輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
 * @Date 2020.3.18
 */
public class TreeDepthsSolutionClass {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode a = new TreeNode(2);
        TreeNode b = new TreeNode(2);
        TreeNode c = new TreeNode(2);
        TreeNode d = new TreeNode(2);
        root.left=a;
        a.left=b;
        b.right=c;
        root.right=d;
        //TreeNode root=null;
        System.out.println(new TreeDepthsSolutionClass().TreeDepth(root));//4
    }

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

總結

上面兩題都涉及到了二叉樹求深度的問題,往往這種類型的題目需要使用遞歸來求解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章