LeetCode_589

先看题目

 

前序遍历N叉树,与前序遍历二叉树类似

可以使用递归或者栈,两种方法

1.使用递归

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public List<Node> children;
 6 
 7     public Node() {}
 8 
 9     public Node(int _val) {
10         val = _val;
11     }
12 
13     public Node(int _val, List<Node> _children) {
14         val = _val;
15         children = _children;
16     }
17 };
18 */
19 
20 class Solution {
21     public List<Integer> preorder(Node root) {
22         List<Integer> res = new LinkedList<>();
23         pre(res,root);
24         return res;
25     }
26     public void pre(List<Integer> res,Node root){
27         if(root == null){
28             return;
29         }
30         res.add(root.val);
31         for(Node node : root.children){
32             pre(res,node);
33         }
34     }
35 }

2.使用栈

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public List<Node> children;
 6 
 7     public Node() {}
 8 
 9     public Node(int _val) {
10         val = _val;
11     }
12 
13     public Node(int _val, List<Node> _children) {
14         val = _val;
15         children = _children;
16     }
17 };
18 */
19 
20 class Solution {
21     public List<Integer> preorder(Node root) {
22         List<Integer> res = new LinkedList<>();
23         if(root == null){
24             return res;
25         }
26         Stack<Node> stack1 = new Stack<>();
27         Stack<Node> stack2 = new Stack<>();
28         
29         stack2.add(root);
30         while(stack2.size() > 0){
31             Node node = stack2.pop();
32             res.add(node.val);
33             for(Node n : node.children){
34                 stack1.add(n);
35             }
36             while(stack1.size() > 0){
37                 stack2.add(stack1.pop());
38             }
39         }
40         return res;
41     }
42 }

 

posted @ 2022-03-10 11:44  雨下_整夜  阅读(12)  评论(0编辑  收藏  举报