LeetCode之二叉树最大深度(简单 二叉树)

问题描述:

给定一个二叉树,找出其最大深度。

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

说明: 叶子节点是指没有子节点的节点。

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

二叉树的问题解决大概基本两个方向,递归,和队列或者栈实现非递归。

递归

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

    }

非递归(这个的非递归有点小难度,因为每次取节点要保存树的深度)

import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
    public int maxDepth(TreeNode root) {
        Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        if (root != null) {
            queue.add(new Pair(root, 1));
        }

        int depth = 0;
        while (!queue.isEmpty()) {
            Pair<TreeNode, Integer> current = queue.poll();
            root = current.getKey();
            int current_depth = current.getValue();
            if (root != null) {
                depth = current_depth;
                queue.add(new Pair(root.left, current_depth + 1));
                queue.add(new Pair(root.right, current_depth + 1));
            }
        }
        return depth;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83502357