leetcode 589. Preorder traversal of N-ary tree (java)

Question description

Difficulty - Easy
LC - 589. Preorder traversal of N-ary tree

Given the root node root of an n-ary tree, return the preorder traversal of its node values.
The n-ary tree is represented serially in the input by level-order traversal, with each set of child nodes separated by the null value (see example).

Example 1:
Insert image description here
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]

Example 2:
Insert image description hereInput: 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: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]

Tip:
The total number of nodes is in the range [0, 10^4]
0 <= Node.val <= 10^4
The height of the n-fork tree is less than or equal to 1000
Insert image description here

Preorder traversal

The recursive idea is relatively simple. The ideas and methods of pre-order traversal of NNN fork trees are basically the same as those of pre-order traversal of binary trees. During each recursion, the root node is visited first, and then each child node is recursively visited in turn.

Code demo:

/*
// 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 {
    
    
    List<Integer> ans = new ArrayList<>();
    public List<Integer> preorder(Node root) {
    
    
        dfs(root);
        return ans;
    }
    
    public void dfs(Node root){
    
    
        if(root == null){
    
    
            return;
        }
        ans.add(root.val);
        for(Node node : root.children){
    
    
            dfs(node);
        }
    }
}

Insert image description here

Postorder traversal

Difficulty - Simple
leetcode - 590. Post-order traversal of N-ary tree

The only difference between post-order traversal and pre-order traversal is that if I add the answer later, if I have written binary tree traversal, I should be able to see the difference directly here. Let’s just look at the code demonstration.

Code demo :

/*
// 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 {
    
    
     List<Integer> ans = new ArrayList<>();
    public List<Integer> postorder(Node root) {
    
    
        dfs(root);
        return ans;
    }

    void dfs(Node root){
    
    
        if(root == null){
    
    
            return ;
        }
        for(Node node : root.children){
    
    
            dfs(node);
        }
        ans.add(root.val);
    }
}

Guess you like

Origin blog.csdn.net/SP_1024/article/details/132808246