首页 > 其他分享 >104. Maximum Depth of Binary Tree[Easy]

104. Maximum Depth of Binary Tree[Easy]

时间:2023-02-03 14:24:49浏览次数:46  
标签:Binary 遍历 return cur Tree Maximum result null root

217. Contains Duplicate

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100

Example
image

Input: root = [3,9,20,null,null,15,7]
Output: 3

思路

熟练掌握三种树的遍历方式

  • 递归遍历
  • 深度遍历
  • 广度遍历

题解

  • 递归遍历
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;

        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
  • 深度遍历
    public int maxDepth(TreeNode root) {
        int result = 0;
        if (root == null)
            return result;

        // 利用栈先进后出的特性
        Stack<TreeNode> stack = new Stack<>();
        // 给第一层赋初值
        root.val = 1;
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            // 先将右子树入栈,这样pop时先访问的就是左子树,左中右遍历
            if (cur.right != null) {
                // 每一层都在上一层的基础上+1
                cur.right.val = cur.val + 1;
                stack.push(cur.right);
            }
            if (cur.left != null) {
                cur.left.val = cur.val + 1;
                stack.push(cur.left);
            }
            result = Math.max(result, cur.val);
        }

        return result;
    }
  • 广度遍历
    public int maxDepth(TreeNode root) {
        int result = 0;
        if (root == null)
            return result;

        // 利用队列先进先出特性
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            // 这边拿到的size其实就是当前层中所有的节点,要把它先存起来,避免下面对队列操作产生影响
            int size = queue.size();
            // 把当前层的节点依次弹出
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                // 从左往右依次入队列
                if (cur.left != null)
                    queue.add(cur.left);
                if (cur.right != null)
                    queue.add(cur.right);
            }
            // 每一层结束记录一下
            result++;
        }

        return result;
    }

标签:Binary,遍历,return,cur,Tree,Maximum,result,null,root
From: https://www.cnblogs.com/tanhaoo/p/17088626.html

相关文章