题目
(1)给定一个 n 叉树的根节点 root ,返回 其节点值的前序遍历 。
(2)n 叉树在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
(3)示例如下:
输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]
解决思路
- 采用递归思想解决。
- 具体步骤:
- 第一步:输出根节点的值。
- 第二步:递归遍历根节点的所有子树。
代码
- C++代码:
# include <stdio.h>
# include <vector>
using namespace std;
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:
// 递归函数实现前序遍历:先将根节点的值放入数组answer的末尾,然后递归遍历根节点的每个子节点。
void mypreorder(Node* root, vector<int>& answer) {
if (root == nullptr) { // 边界条件
return;
}
answer.push_back(root->val); // 第一步:输出根节点的值(将根节点的值放入数组answer的末尾)。
for (auto c: root->children) { // 第二步:递归遍历根节点的所有子树。
mypreorder(c, answer);
}
}
vector<int> preorder(Node* root) {
if (nullptr == root) {
return vector<int> ();
}
vector<int> answer;
mypreorder(root, answer);
return answer;
}
};
int main() {
Node* n1 = new Node(1);
Node* n2 = new Node(3);
Node* n3 = new Node(2);
Node* n4 = new Node(4);
Node* n5 = new Node(5);
Node* n6 = new Node(6);
n1->children.push_back(n2);
n1->children.push_back(n3);
n1->children.push_back(n4);
n2->children.push_back(n5);
n2->children.push_back(n6);
Node* root = n1;
Solution* solution = new Solution();
vector<int> ret = solution->preorder(root);
for (auto r: ret) {
printf("%d ", r);
}
printf("\n");
return 0;
}
- Python代码
# -*- coding: utf-8 -*-
from typing import List
class Node:
def __init__(self, _val=0, _chaildren=None):
self.val = _val
self.children = _chaildren
class Solution:
def __init__(self):
pass
def mypreorder(self, root, answer: List[int]):
if None == root:
return
answer.append(root.val)
if root.children:
for c in root.children:
self.mypreorder(c, answer)
def preorder(self, root) -> List[int]:
answer: List[int] = []
self.mypreorder(root, answer)
return answer
def main():
n1 = Node(1)
n2 = Node(3)
n3 = Node(2)
n4 = Node(4)
n5 = Node(5)
n6 = Node(6)
n1.children = [n2, n3, n4]
n2.children = [n5, n6]
solution = Solution()
print(solution.preorder(n1))
if __name__ == "__main__":
main()
说明
- 对应LeetCode第589题。
- 链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/