算法20(递归)-二叉树的深度

题目:

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

3

/
9 20
/
15 7
return its depth = 3.

给一个二叉树,将他的最大深求出来并且进行输出
1.采用递归的思想,停止递归的条件是根节点没有左子树并且没有右子树,就返回0,
2.递归做什么事情,递归左子树,递归右子树,找到两个子树深度最大值,再进行加3.返回的就是两个子树深度最大值加1

package com.cxy.recursive;

import com.cxy.linkedtable.TreeNode;

import java.util.List;

/**
 * 二叉树的深度优先搜索递归实现
 */
public class BinaryTreeDepth {

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


  public static void main(String[] args){
    TreeNode left = new TreeNode(1, null, null);
    TreeNode right = new TreeNode(2, null, null);
    TreeNode root = new TreeNode(0, left, right);
    int depth = new BinaryTreeDepth().maxDepth(root);
    System.out.println(depth);
  }

}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1371769065@qq.com

文章标题:算法20(递归)-二叉树的深度

字数:259

本文作者:一叶知秋

发布时间:2020-07-04, 16:36:08

最后更新:2020-07-04, 16:37:04

原始链接:http://yoursite.com/2020/07/04/arithmtic/20-%E9%80%92%E5%BD%92/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

×

喜欢就点赞,疼爱就打赏

相册 github