LeetCode——N-ary Tree Postorder Traversal(590)
阿新 • • 發佈:2018-12-11
Given an n-ary tree, return the postorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its postorder traversal as: [5,6,3,2,4,1]
.
分析:
典型的樹遍歷
程式碼:
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ static const auto __ = []() { ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: vector<int> postorder(Node* root) { vector<int> ress; stack<Node*> res; if(!root) return ress; Node* temp; res.push(root); while(!res.empty()) { temp = res.top(); res.pop(); for(int i=0;i<temp->children.size();++i) res.push(temp->children[i]); ress.push_back(temp->val); } reverse(ress.begin(), ress.end()); return ress; } };