計算二叉樹的最大深度

class TreeNode{
    int val;//當前節點的值
    TreeNode left; //左節點
    TreeNode right;//右節點
    TreeNode(int x){
        val=x;//通過構造方法傳值
    }
}
public class haha{
    public static int maxDepth(TreeNode root){
        if(root==null)
            return 0;
        return  1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }

    public static void main(String[] args) {
        TreeNode root=new TreeNode(3);
        TreeNode t1=new TreeNode(5);
        TreeNode t2=new TreeNode(7);
        t1.left=t2;
        TreeNode t3=new TreeNode(9);
        root.left=t1;
        root.right=t3;
        System.out.println(maxDepth(root));
    }
}

 

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