Given an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class NAryTreePreorderTra {static List<Integer> list = null;public static void main(String[] args) {// 3 node childList<Node> node3Child = new ArrayList<Node>();node3Child.add(new Node(5));node3Child.add(new Node(6));// 1 node childList<Node> node1Child = new ArrayList<Node>();node1Child.add(new Node(3, node3Child));node1Child.add(new Node(2));node1Child.add(new Node(4));// root nodeNode node = new Node(1, node1Child);list = new ArrayList<>();preOrder(node);System.out.println(Arrays.asList(list));}// method to pre-orderpublic static void preOrder(Node root) {if (root == null)return;list.add(root.val);List<Node> child = root.children;if (child != null) {for (Node c : child) {preOrder(c);}}}}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;}};
C++
#include <bits/stdc++.h>using namespace std;//structure of the nodestruct Node{int val;vector<Node*> children;Node() {}Node(int _val) {val = _val;}Node(int _val, vector<Node*> _children) {val = _val;children = _children;}};//function for pre-order traversalvector<int> preOrder(Node* root){vector<int> res;if(root==NULL)return res;stack<Node*> st;st.push(root);while(!st.empty()){Node *curr=st.top();st.pop();res.push_back(curr->val);for(auto it=curr->children.rbegin();it!=curr->children.rend();it++)st.push(*it);}return res;}int main(){// 3 node childvector<Node*> node3Child;node3Child.push_back(new Node(5));node3Child.push_back(new Node(6));// 1 node childvector<Node*> node1Child;node1Child.push_back(new Node(3, node3Child));node1Child.push_back(new Node(2));node1Child.push_back(new Node(4));// root nodeNode *node = new Node(1, node1Child);vector<int> result=preOrder(node);for(int i=0;i<result.size();i++)cout<<result[i]<<" ";return 0;}
No comments:
Post a Comment