Maximum Depth of Binary Tree:二叉树深度

来源:互联网 发布:大野克夫的水平知乎 编辑:程序博客网 时间:2024/05/21 14:55

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:标准的深度优先遍历,没什么可说的。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    int max = 0;    public void dfs(TreeNode n,int depth)    {        if(n==null) return;        max = Math.max(max,depth);        dfs(n.left,depth+1);        dfs(n.right,depth+1);    }     public int maxDepth(TreeNode root) {        if(root == null) return 0;        dfs(root,1);        return max;    }}




阅读全文
0 0
原创粉丝点击