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<int> postorder(Node* root) {
    	vector<int> ret;
		if(!root)
    		return ret;
    	int length = root->children.size();
    	for(int i=0;i<length;i++){
    		vector<int> temp = postorder(root->children[i]);
    		ret.insert(ret.end(),temp.begin(),temp.end());
		}
		ret.push_back(root->val);
		return ret;
    }
};

AC,beats 98%

猜你喜欢

转载自blog.csdn.net/qq_29303759/article/details/81329058