LeetCode-面试题55 - I. 二叉树的深度-深度优先搜索

/** 面试题55 - I. 二叉树的深度

* @author 作者 Your-Name:

* @version 创建时间:2020年2月29日 下午9:06:48

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

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。


*/

public class 二叉树的深度 {
	public class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	  }
	int max=0;
	public int maxDepth(TreeNode root) {
		if(root==null)
			return 0;
		return DFS(root,max);
		
    }
	public int DFS(TreeNode root,int max)
	{
		if(root==null)
			return max;
		return Math.max(DFS(root.left,max+1), DFS(root.right,max+1));
			
	}
}
发布了72 篇原创文章 · 获赞 7 · 访问量 4107

猜你喜欢

转载自blog.csdn.net/l769440473/article/details/104669757