LC589 N叉树的前序遍历
1.读题
给定一个 N 叉树,返回其节点值的 前序遍历 。
N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
提示:
- N 叉树的高度小于或等于 1000
- 节点总数在范围 [0, 10^4] 内
实例1
输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]
实例2
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]
2.思路
就递归就完事了~
简单难度的题嘛 相比于 LC144 不需要考虑左子树和右子树的遍历
只需要
在遍历到的节点仍是节点的子节点时 递归就完事了!
即为使用——
for(auto x : root->children)
做判断(这个语句的意思是迭代容器中所有的元素 每个元素的临时名字为x)
3. 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:
void __preorder(Node *root,vector<int> &res) {
if (root == NULL) return; //退出条件
res.push_back(root->val); //节点值入队列
for(auto x : root->children)
//迭代容器中所有的元素 每个元素的临时名字为x
__preorder(x,res); //递归遍历
}
}
vector<int> preorder(Node* root) {
vector<int> res;
__preorder(root,res);
return res;
}
};
4.python代码实现
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root:'Node') -> List[int]:
result = [] #结果数组
#前序遍历
def pre_order(root):
if root:
result.append(root.val)
for node in root.children:
pre_order(node)
pre_order(root)
return result
python写起来就简单得多辽!
5.JAVA代码
class Solution {
public List<Integer> preorder(Node root) {
LinkedList<Node> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
stack.add(root);
while (!stack.isEmpty()) {
Node node = stack.pollLast();
output.add(node.val);
Collections.reverse(node.children);
for (Node item:node.children) {//遍历完所有子节点为止
stack.add(item);
}
}
return output;
}
}
再放一个简单点的方法~
class Solution {
List<Integer> res = new ArrayList<Integer>();
public List<Integer> preorder(Node root) {
if (root == null){
return res;
}
res.add(root.val);//节点值挨个入队列~
// 遍历N叉树的所有节点!每个节点的临时名字为child
for (Node child:root.children){
preorder(child);
}
return res;
}
}