美文网首页
剑指 Offer 55 - I 二叉树的深度

剑指 Offer 55 - I 二叉树的深度

作者: itbird01 | 来源:发表于2021-12-25 00:06 被阅读0次
题目.png

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

解题思路

解法1:DFS
1.分析题意,树的后序遍历 / 深度优先搜索往往利用 递归 或 栈 实现,解法1递归求解
2.如果root为空,肯定返回0,然后返回Math.max(maxDepth(root.left), maxDepth(root.right)) + 1即可

解法1:BFS
1.分析题意,广度优先搜索往往利用 队列 实现
2.使用队列进行层序遍历即可

解题遇到的问题

后续需要总结学习的知识点

##解法1
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }
}

##解法2
import java.util.LinkedList;

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        LinkedList<TreeNode> linkedList = new LinkedList<TreeNode>();
        linkedList.add(root);
        int ans = 0;
        while (!linkedList.isEmpty()) {
            LinkedList<TreeNode> temp = new LinkedList<TreeNode>();
            while (!linkedList.isEmpty()) {
                TreeNode node = linkedList.pop();
                if (node.left != null) {
                    temp.add(node.left);
                }
                if (node.right != null) {
                    temp.add(node.right);
                }
            }
            linkedList.addAll(temp);
            ans++;
        }
        return ans;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }
}

相关文章

网友评论

      本文标题:剑指 Offer 55 - I 二叉树的深度

      本文链接:https://www.haomeiwen.com/subject/vqwlqrtx.html