题目:
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
image.png
返回其后序遍历: [5,6,3,2,4,1].
说明: 递归法很简单,你可以使用迭代法完成此题吗?
链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal
思路:
1、后序遍历的顺序是【左右根】,那就递归的按照先子树后根节点的顺序进行遍历
Python代码:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def __init__(self):
self.ret = []
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return None
for child in root.children:
self.postorder(child)
self.ret.append(root.val)
return self.ret
C++代码:
/*
// 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;
}
};
*/
class Solution {
public:
vector<int> ret;
vector<int> postorder(Node* root) {
if (root == nullptr) {
return ret;
}
for (auto child : root->children){
postorder(child);
}
ret.push_back(root->val);
return ret;
}
};
网友评论