zoukankan      html  css  js  c++  java
  • LeetCode 589. N叉树的前序遍历

    给定一个 N 叉树,返回其节点值的前序遍历。

    例如,给定一个 3叉树 :

     

    返回其前序遍历: [1,3,5,6,2,4]。

    说明: 递归法很简单,你可以使用迭代法完成此题吗?

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal

    递归:

     1 void process(Node* root,vector<int> &ans) {
     2     ans.push_back(root->val);
     3     int n = root->children.size();
     4 
     5     for(int i = 0; i < n; i++)
     6     {
     7         process(root->children[i],ans);
     8     }
     9 }
    10 vector<int> preorder(Node* root) {
    11     vector<int> ans;
    12     if(root)
    13         process(root,ans);
    14     return ans;
    15 }

    迭代:

     1 /*
     2 // Definition for a Node.
     3 class Node {
     4 public:
     5     int val;
     6     vector<Node*> children;
     7 
     8     Node() {}
     9 
    10     Node(int _val, vector<Node*> _children) {
    11         val = _val;
    12         children = _children;
    13     }
    14 };
    15 */
    16 class Solution {
    17 public:
    18     vector<int> preorder(Node* root) {
    19         vector<int> ans;
    20         if(!root) return ans;
    21         stack<Node*> nodeStack;
    22         nodeStack.push(root);
    23         while(!nodeStack.empty()) {
    24             Node* node = nodeStack.top();
    25             ans.push_back(node->val);
    26             nodeStack.pop();
    27             int n = node->children.size();
    28             for(int i = n-1; i >= 0 ; i--)
    29             {
    30                 nodeStack.push(node->children[i]);
    31             }
    32         }
    33         return ans;
    34     }
    35 };
  • 相关阅读:
    php 下设置cookie问题
    js 页面无滚动条添加滚轮事件
    Python中关于字符串的问题
    Python 字符串相加问题
    ajax 同步和异步
    重叠div鼠标经过事件
    Myeclipse中将项目上传到码云
    eclipse debug的时候提示debug Edit Source Lookup path
    阿里云+wordpress搭建个人博客网站
    centos7 安装mysql
  • 原文地址:https://www.cnblogs.com/jj81/p/11486812.html
Copyright © 2011-2022 走看看