二叉树的深度

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

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

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

上一篇:剑指 Offer 55 - I. 二叉树的深度


下一篇:第35期:从 DFS 学习二叉树!(适合小白)