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

题目:

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);
  }

}

你可能感兴趣的:(算法--(递归)--二叉树的深度遍历)