zoukankan      html  css  js  c++  java
  • 【leetcode】589. N-ary Tree Preorder Traversal

    题目:

    Given an n-ary tree, return the preorder traversal of its nodes' values.

    For example, given a 3-ary tree:

    Return its preorder traversal as: [1,3,5,6,2,4].

    Note:

    Recursive solution is trivial, could you do it iteratively?

     
    1. Recursive solution:
     
    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        vector<Node*> children;
    
        Node() {}
    
        Node(int _val, vector<Node*> _children) {
            val = _val;
            children = _children;
        }
    };
    */
    class Solution {    
    public:
        vector<int> preorder(Node* root) {
            vector<int> order = {};
            if (root) {
                traversal(root, order);
            }
            
            return order;
        }
        
        void traversal(Node* root, vector<int> &order) {
            order.push_back(root->val);
            int num = root->children.size();
            for (int i = 0; i < num; i++) {
                traversal(root->children.at(i), order);
            }
        }
    };
    

      

    2. Iterative  solution:

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        vector<Node*> children;
    
        Node() {}
    
        Node(int _val, vector<Node*> _children) {
            val = _val;
            children = _children;
        }
    };
    */
    class Solution {    
    public:
        vector<int> preorder(Node* root) {
            vector<int> order = {};
            stack<Node*> nodeStack;
            if (root) {
                nodeStack.push(root);
            }
            
            while (!nodeStack.empty()) {
                Node* node = nodeStack.top();
                nodeStack.pop();
                order.push_back(node->val);
                int num = node->children.size();
                for (int i = num - 1; i >= 0; i--) {
                    nodeStack.push(node->children.at(i));
                }
            }
            
            return order;
        }
        
    };
    

      

  • 相关阅读:
    echarts 立体图
    css 设置边框边角
    PS2020 快速设置文字渐变
    idea 2019 永久破解
    使用VUE+element ui 实现输入框 占位符自动补全功能
    纯css 设置隔行样式
    CSS 设置float:left 导致后面元素错乱问题
    c primer plus 4编程练习
    c语言中以八进制数表示字符、并输出
    c语言中printf()函数的返回值
  • 原文地址:https://www.cnblogs.com/AndrewGhost/p/10348109.html
Copyright © 2011-2022 走看看