Given an n-ary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class NAryTreePostorderTra {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<>();postOrder(node);System.out.println(Arrays.asList(list));}// method to post-orderpublic static void postOrder(Node root) {if (root == null)return;List<Node> child = root.children;if (child != null) {for (Node c : child) {postOrder(c);}}list.add(root.val);}}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;struct Node{int val;vector<Node*> children;Node() {}Node(int _val){val = _val;}Node(int _val, vector<Node*> _children){val = _val;children = _children;}};//function for postorder traversalvector<int> postOrder(Node* root){stack<Node *> st;vector<int> res;if(root==NULL)return res;st.push(root);Node *curr=NULL;while(!st.empty()){curr=st.top();res.push_back(curr->val);st.pop();for(auto it=curr->children.begin();it!=curr->children.end();it++)st.push(*it);}reverse(res.begin(),res.end());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=postOrder(node);for(int i=0;i<result.size();i++)cout<<result[i]<<" ";return 0;}
No comments:
Post a Comment