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

For example, given a 3-ary tree:

 

LeetCode-589. N-ary Tree Preorder Traversal

 

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

 

Note:

Recursive solution is trivial, could you do it iteratively?

题解:

class Solution {
public:
  static void preOrder(Node* root, vector<int> &ans) {
    if (root != NULL) {
      ans.push_back(root->val);
      for (int i = 0; i < root->children.size(); i++) {
        preOrder(root->children[i], ans);
      }    
    }
  }
  vector<int> preorder(Node* root) {
    vector<int> ans;
    preOrder(root, ans);
    return ans;
  }
};

 

相关文章:

  • 2022-12-23
  • 2021-09-22
  • 2021-06-28
  • 2021-10-04
  • 2022-02-10
  • 2021-06-28
  • 2021-12-15
  • 2021-09-27
猜你喜欢
  • 2021-10-24
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
  • 2021-07-26
  • 2021-10-15
相关资源
相似解决方案