LeetCode-590. N-ary Tree Postorder Traversal

Given an n-ary tree, return the preorder traversal of its nodes' values.

For example, given a 3-ary tree:

Return its preorder traversal as: [1,3,5,6,2,4]

Note: Recursive solution is trivial, could you do it iteratively?

题目:N叉树的后续遍历,先从左到右遍历孩子,再遍历根节点。

思路:note说最好用迭代的做。而我还是用的递归\(^o^)/。代码如下:

class Solution {
public:
    vector postorder(Node* root) {
    	vector ret;
		if(!root)
    		return ret;
    	int length = root->children.size();
    	for(int i=0;i temp = postorder(root->children[i]);
    		ret.insert(ret.end(),temp.begin(),temp.end());
		}
		ret.push_back(root->val);
		return ret;
    }
};

AC,beats 98%

你可能感兴趣的:(LeetCode-C++,C/C++,LeetCode,Tree,N-Tree)