两种得到二叉树深度的递归方法

两种得到二叉树深度的递归方法

  • 104. 二叉树的最大深度
    • 题目分析
      • 代码1
      • 代码2

104. 二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

两种得到二叉树深度的递归方法_第1张图片

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。
  • -100 <= Node.val <= 100

题目分析

递归二叉树的深度有两种方法,一种就是直接采用递归,递归到叶子结点之后返回,记录左子树和右子树的深度,取它们的最大值加1为二叉树的深度

代码1

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

还有一种方式就是我们可以在递归的过程中记录当前已经遍历过的结点个数,设置一个全局变量,实时更新最大值

代码2

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int ans = 0;
    
    public int maxDepth(TreeNode root) {
        f(root, 0);
        return ans;
    }
    public void f(TreeNode root, int cnt){
        if(root == null)
            return ;
        cnt ++;
        this.ans = Math.max(ans, cnt);
        f(root.left, cnt);
        f(root.right, cnt);
    }
}

你可能感兴趣的:(跟着灵茶山学算法,算法,leetcode,数据结构)