LeetCode 104. Maximum Depth of Binary Tree

Problem Description

  • 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.

  • address

problem analysis

  • Find the maximum depth of the binary tree: the classic routine solution of the binary tree: DFS recursion
  • Methods 2 and 3 also provide solutions without recursion:
    • Method 2: A non-recursive implementation of pre-order traversal , one stack stores nodes, and the other stack stores the depth of the corresponding nodes. Therefore, instead of two stacks, you can directly encapsulate the node and its height into an object and put it into a stack.
    • Method 2: Layer order traversal BFS

Code

  • Method 1: DFS recursion
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
  • Method 2: Preorder traversal non-recursive
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> depthStack = new Stack<>();
        int maxDepth = 0;
        nodeStack.add(root);
        depthStack.add(1);
        while (! nodeStack.isEmpty()) {
            TreeNode popNode = nodeStack.pop();
            int curDepth = depthStack.pop();
            maxDepth = Math.max(maxDepth, curDepth);
            if (popNode.right != null) {
                nodeStack.add(popNode.right);
                depthStack.add(curDepth + 1);
            }
            if (popNode.left != null) {
                nodeStack.add(popNode.left);
                depthStack.add(curDepth + 1);
            }
        }
        return maxDepth;
    }
  • Method 3: Layer order traversal BFS
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int maxDepth = 0;
        while(! queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; ++i) {
                TreeNode popNode = queue.poll();
                if (popNode.left != null) {
                    queue.add(popNode.left);
                }
                if (popNode.right != null) {
                    queue.add(popNode.right);
                }
            }
            ++maxDepth;
        }
        return maxDepth;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324669537&siteId=291194637