590. N-ary Tree Postorder Traversal

LeetCode easy original: C# #csharp #easy #leetcode #stack #tree
题目文本会按所选界面语言从俄语翻译;代码保持不变。

given корневое 树 с n-арной структурой, return обход дерева в постфиксном порядке для значений его узлов.

Сериализация 输入ных данных n-арного дерева представлена в обходе уровней. Каждая группа детей разделяется значением null (см. 示例ы).

示例:

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

C# 解法

匹配/原始
using System.Collections.Generic;
public class Node {
    public int val;
    public IList<Node> children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, IList<Node> _children) {
        val = _val;
        children = _children;
    }
}
public class Solution {
    public IList<int> Postorder(Node root) {
        LinkedList<int> output = new LinkedList<int>();
        if (root == null) {
            return output;
        }
        Stack<Node> stack = new Stack<Node>();
        stack.Push(root);
        
        while (stack.Count > 0) {
            Node node = stack.Pop();
            output.AddFirst(node.val);
            foreach (Node child in node.children) {
                if (child != null) {
                    stack.Push(child);
                }
            }
        }
        
        return new List<int>(output);
    }
}

C++ 解法

自动草稿,提交前请检查
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class Node {
    public int val;
    public IList<Node> children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, IList<Node> _children) {
        val = _val;
        children = _children;
    }
}
class Solution {
public:
    public vector<int> Postorder(Node root) {
        LinkedList<int> output = new LinkedList<int>();
        if (root == null) {
            return output;
        }
        stack<Node> stack = new stack<Node>();
        stack.push(root);
        
        while (stack.size() > 0) {
            Node node = stack.pop();
            output.AddFirst(node.val);
            foreach (Node child in node.children) {
                if (child != null) {
                    stack.push(child);
                }
            }
        }
        
        return new List<int>(output);
    }
}

Java 解法

匹配/原始
class Solution {
    public List<Integer> postorder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }

        stack.add(root);
        while (!stack.isEmpty()) {
            Node node = stack.pollLast();
            output.addFirst(node.val);
            for (Node item : node.children) {
                if (item != null) {
                    stack.add(item);
                }
            }
        }
        return output;
    }
    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

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

JavaScript 解法

匹配/原始
function Node(val, children) {
    this.val = val;
    this.children = children ? children : [];
}

var postorder = function(root) {
    if (!root) return [];
    
    const stack = [root];
    const output = [];
    
    while (stack.length) {
        const node = stack.pop();
        output.unshift(node.val);
        for (const child of node.children) {
            stack.push(child);
        }
    }
    
    return output;
};

Python 解法

匹配/原始
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if not root:
            return []
        
        stack, output = [root], []
        while stack:
            node = stack.pop()
            output.append(node.val)
            stack.extend(node.children)
        
        return output[::-1]

Go 解法

匹配/原始
package main

type Node struct {
    Val      int
    Children []*Node
}

func postorder(root *Node) []int {
    if root == nil {
        return []int{}
    }
    
    stack := []*Node{root}
    output := []int{}
    
    for len(stack) > 0 {
        node := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        output = append([]int{node.Val}, output...)
        for _, child := range node.Children {
            if child != nil {
                stack = append(stack, child)
            }
        }
    }
    
    return output
}

Algorithm

Инициализируйте стек для хранения узлов и список для хранения значений узлов в обратном порядке.

Начните с корневого узла и добавьте его в стек. Пока стек не пуст, извлекайте узлы из стека, добавляя их значения в начало списка, и добавляйте всех его детей в стек.

В конце return список значений узлов.

😎

Vacancies for this task

活跃职位 with overlapping task tags are 已显示.

所有职位
目前还没有活跃职位。