树590. N叉树的后序遍历
Posted ocpc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树590. N叉树的后序遍历相关的知识,希望对你有一定的参考价值。
题目:
解答:
方法一:递归
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val) { 11 val = _val; 12 } 13 14 Node(int _val, vector<Node*> _children) { 15 val = _val; 16 children = _children; 17 } 18 }; 19 */ 20 21 class Solution { 22 public: 23 vector<int> postorder(Node* root) 24 { 25 vector<int> result; 26 if (NULL == root) 27 { 28 return result; 29 } 30 31 recursivePostorder(root, result); 32 return result; 33 } 34 35 void recursivePostorder(Node *root, vector<int> &ret) 36 { 37 if (NULL == root) 38 { 39 return; 40 } 41 42 int size = root->children.size(); 43 for (int i = 0; i < size; i++) 44 { 45 Node *n = root->children[i]; 46 if (n) 47 { 48 recursivePostorder(n, ret); 49 } 50 } 51 52 ret.push_back(root->val); 53 } 54 };
方法二:迭代
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val) { 11 val = _val; 12 } 13 14 Node(int _val, vector<Node*> _children) { 15 val = _val; 16 children = _children; 17 } 18 }; 19 */ 20 21 class Solution { 22 public: 23 // 第二种:迭代, 先前序,然后反转 24 vector<int> postorder(Node* root) { 25 vector<int> ve; 26 if (!root) return ve; 27 28 stack<Node*> st; 29 st.push(root); 30 31 while (!st.empty()) { 32 Node *node = st.top(); 33 st.pop(); 34 35 if (node) { 36 ve.emplace_back(node->val); 37 38 vector<Node*> chs = node->children; 39 if (!chs.empty()) { 40 int size = chs.size(); 41 for (int i =0; i< size; i++) { 42 Node *n = chs[i]; 43 if (n) st.push(n); 44 } 45 } 46 } 47 } 48 49 reverse(ve.begin(),ve.end()); 50 return ve; 51 } 52 53 };
以上是关于树590. N叉树的后序遍历的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Algorithm 590. N 叉树的后序遍历