遇见YY

导航

 

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

思考递归(例如对于关于树的相关操作):要从树叶到树根思考代码的运行过程!

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

    TreeNode(int x) {
        val = x;
    }
}


class Solution {
   public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(9);
        node.right = new TreeNode(20);
        node.right.left = new TreeNode(15);
        node.right.right = new TreeNode(7);
        Solution solution = new Solution();
        int depth = solution.maxDepth(node);
        System.out.println("depth: " + depth);
    }


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


}

题目来源:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof

posted on 2020-09-22 09:58  一骑红尘妃子笑!  阅读(129)  评论(0编辑  收藏  举报