LeetCode brush questions - maximum depth of N-ary tree

Preface description

Algorithm learning, daily problem brushing records.

Topic connection

Maximum depth of N-ary tree

Topic content

Given an N-ary tree, find its maximum depth.

The maximum depth is the total number of nodes on the longest path from the root node to the farthest leaf node.

N-ary tree input is represented by sequence traversal serialization, with each group of child nodes separated by null values (see example).

Example 1:

Input: root = [1,null,3,2,4,null,5,6]

Output: 3

Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

Output: 5

Tips:

The depth of the tree will not exceed 1000.

The number of nodes in the tree is between [0, 10 ^ 4].

Analysis process

Idea: depth first search, using recursion. If a tree has n nodes and maxChildDepth is the maximum depth of N nodes, the maximum depth of the tree is n+1.

First step

If the node is empty, 0 is returned.

Step 2

Define the maximum child node depth maxChildDepth, which is initially 0; Get the child node children of the node and traverse the child node children.

Step 3

During each traversal, recursively call its own function maxDepth to obtain the maximum depth of each child node, which is defined as childDepth. Compare it with the current maximum child node depth maxChildDepth, take the maximum value, and update it to the maximum child node depth maxChildDepth.

Step 4

Finally, return the maximum child node depth maxChildDepth plus 1, which is the maximum depth of the n-ary tree, and end the program.

Answer code

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public int maxDepth(Node root) {
        // Depth first search. If a tree has n nodes and maxChildDepth is the maximum depth of N nodes, the maximum depth of the tree is n+1

        if (root == null) {
            // If the node is empty, 0 is returned
            return 0;
        }

        // Define maximum child node depth
        int maxChildDepth = 0;

        // Gets the child node of the node
        List<Node> children = root.children;

        if (children != null) {
            // Traverse child nodes
            for (Node node : children) {
                // Recursively call itself to obtain the maximum depth of each child node
                int childDepth = maxDepth(node);

                // Compare with the current maximum child node depth, take the maximum value and update to the maximum child node depth
                maxChildDepth = Math.max(maxChildDepth, childDepth);
            }
        }

        // Returns the maximum child node depth plus 1, which is the maximum depth of the n-ary tree
        return maxChildDepth + 1;
    }
}

Submit results

The execution time is 1ms, the time beats 100.00% of users, the memory consumption is 38.7MB, and the space beats 10.62% of users.

Extension analysis

However, the code for converting the input array into an N-ary tree is not given in the title. When you brush the title on LeetCode, the LeetCode background has done the conversion for you. However, if we want to write the complete code ourselves, we need to do the conversion ourselves. The idea is similar to the previous array to binary tree. Breadth first search is realized through queue assistance, That is, simulate the process of sequence traversal from top to bottom and from left to right, and convert the array into an N-ary tree. However, the difference here is that each group of child nodes is separated by null values. Instead, queue out operation is carried out only when null values are encountered.

Array to binary tree, see the article: LeetCode brush questions - I can flip the binary tree. Does Google want me?

The complete code is as follows:

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // Get input results
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        scanner.close();

        // Process input results
        Integer[] nums;
        if ("[]".equals(str)) {
            // When the array is empty
            nums = null;
        } else {
            // When the array is not empty
            String[] strs = str.split("\\[")[1].split("]")[0].split(",");
            int size = strs.length;
            nums = new Integer[size];
            for (int i = 0; i < size; ++i) {
                if ("null".equals(strs[i])) {
                    nums[i] = null;
                } else {
                    nums[i] = Integer.parseInt(strs[i]);
                }
            }
        }

        // Convert array to N-ary tree
        Node root = arrayToTreeNode(nums);

        // Get output results
        int result = maxDepth(root);
        System.out.println(result);
    }

    // The array is transformed into an N-ary tree, the sequence is traversed, and the layers are in the order from top to bottom and from left to right
    private static Node arrayToTreeNode(Integer[] nums) {
        // With queue assistance, N-ary tree input is represented by sequence traversal serialization, and each group of child nodes is separated by null values
        // Examples: [1,null,3,2,4,null,5,6], [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

        if (nums == null || nums.length == 0) {
            // If the N-ary tree node is empty, it returns null directly
            return null;
        }

        // Start subscript of array
        int i = 1;

        // First construct the root node of N-ary tree
        Node root = new Node(nums[0]);

        // Define the current N-ary tree node and save the temporary value
        Node current = null;

        // Defines the value of the current array
        Integer value;

        // Define a queue and create an N-ary tree
        Queue<Node> queue = new LinkedList<>();

        // Put the root node of the N-ary tree into the queue first, and finally
        queue.add(root);

        // Traverse the array and construct an N-ary tree
        while (i < nums.length) {
            if (nums[i] == null) {
                // If the node value is empty, add 1 to the subscript
                ++i;

                // If the node value is empty, queue out the elements and get the current parent node
                current = queue.poll();
            } else {
                // Gets the value of the array, with the array subscript plus 1
                value = nums[i++];

                // Creates the child of the current parent node
                Node node = new Node(value);

                if (current == null) {
                    current = new Node();
                }

                if (current.children == null) {
                    current.children = new ArrayList<>();
                }

                // Add child to current parent node
                current.children.add(node);

                // List the children of the current parent node
                queue.add(node);
            }
        }

        // Returns the root node of the N-ary tree
        return root;
    }

    private static int maxDepth(Node root) {
        // Depth first search. If a tree has n nodes and maxChildDepth is the maximum depth of N nodes, the maximum depth of the tree is n+1

        if (root == null) {
            // If the node is empty, 0 is returned
            return 0;
        }

        // Define maximum child node depth
        int maxChildDepth = 0;

        // Gets the child node of the node
        List<Node> children = root.children;

        if (children != null) {
            // Traverse child nodes
            for (Node node : children) {
                // Recursively call itself to obtain the maximum depth of each child node
                int childDepth = maxDepth(node);

                // Compare with the current maximum child node depth, take the maximum value and update to the maximum child node depth
                maxChildDepth = Math.max(maxChildDepth, childDepth);
            }
        }

        // Returns the maximum child node depth plus 1, which is the maximum depth of the n-ary tree
        return maxChildDepth + 1;
    }

}

// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};

The arrayToTreeNode method converts the input array into an N-ary tree.

Complete code acquisition: https://github.com/zjhpure/algorithmPractice/blob/master/src/main/java/org/pure/algorithm/maximumDepthOfNAryTree/Main.java

Original link

Original link: Maximum depth of N-ary tree

Tags: Java Algorithm leetcode

Posted on Sun, 21 Nov 2021 20:39:37 -0500 by mitwess