/*// Definition for a Node.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; }};*/classSolution{privateList<Integer>ans=newArrayList<>();publicList<Integer>postorder(Noderoot){dfs(root);returnans;}privatevoiddfs(Noderoot){if(root==null){return;}for(Nodechild:root.children){dfs(child);}ans.add(root.val);}}
/*// Definition for a Node.class Node {public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; }};*/classSolution{public:vector<int>postorder(Node*root){vector<int>ans;function<void(Node*)>dfs=[&](Node*root){if(!root){return;}for(auto&child:root->children){dfs(child);}ans.push_back(root->val);};dfs(root);returnans;}};
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcpostorder(root*Node)(ans[]int){vardfsfunc(*Node)dfs=func(root*Node){ifroot==nil{return}for_,child:=rangeroot.Children{dfs(child)}ans=append(ans,root.Val)}dfs(root)return}
/*// Definition for a Node.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; }};*/classSolution{publicList<Integer>postorder(Noderoot){LinkedList<Integer>ans=newLinkedList<>();if(root==null){returnans;}Deque<Node>stk=newArrayDeque<>();stk.offer(root);while(!stk.isEmpty()){root=stk.pollLast();ans.addFirst(root.val);for(Nodechild:root.children){stk.offer(child);}}returnans;}}
/*// Definition for a Node.class Node {public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; }};*/classSolution{public:vector<int>postorder(Node*root){vector<int>ans;if(!root){returnans;}stack<Node*>stk{{root}};while(!stk.empty()){root=stk.top();ans.push_back(root->val);stk.pop();for(Node*child:root->children){stk.push(child);}}reverse(ans.begin(),ans.end());returnans;}};
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcpostorder(root*Node)[]int{varans[]intifroot==nil{returnans}stk:=[]*Node{root}forlen(stk)>0{root=stk[len(stk)-1]stk=stk[:len(stk)-1]ans=append([]int{root.Val},ans...)for_,child:=rangeroot.Children{stk=append(stk,child)}}returnans}