这篇文章给大家分享的是有关LeetCode如何实现N叉树的前序遍历的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
一,N叉树的前序遍历
1,问题简述
给定一个 N 叉树,返回其节点值的前序遍历。
2,示例描述
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
3,题解思路
递归思想的解决
4,题解程序
import java.util.ArrayList;
import java.util.List;
public class Preordertest4 {
public static void main(String[] args) {
Node node = new Node(1);
Node node2 = new Node(3);
Node node3 = new Node(2);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
List<Node> nodeList1 = new ArrayList<>();
List<Node> nodeList2 = new ArrayList<>();
nodeList2.add(node5);
nodeList2.add(node6);
nodeList1.add(node2);
nodeList1.add(node3);
nodeList1.add(node4);
node2.children = nodeList2;
node.children = nodeList1;
List<Integer> list = preorder(node);
System.out.println("list = " + list);
}
public static List<Integer> preorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
dfs(root, list);
return list;
}
private static void dfs(Node root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
if (root.children == null) {
return;
}
List<Node> children = root.children;
for (Node node : children
) {
dfs(node, list);
}
}
static class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
}
@H_502_105@感谢各位的阅读!关于“LeetCode如何实现N叉树的前序遍历”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。