LeetCode-N-ary Tree Preorder Traversal
Description:
Given an n-ary tree, return the preorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note: Recursive solution is trivial, could you do it iteratively?
题意:返回一颗N叉树的前序遍历节点值;
解法一(递归):将根节点的值插入到list中,对根节点,我们依次遍历他的所有子节点,对每一个子节点递归调用自身;
Java
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
List<Integer> result = new ArrayList<>();
public List<Integer> preorder(Node root) {
if (root == null) return result;
result.add(root.val);
for (Node node : root.children) {
preorder(node);
}
return result;
}
}
解法二(非递归):要想使用非递归实现前序遍历,我们需要利用一个栈来存储子节点;对每一个节点,我们从他的最后节点依次到最左节点存入到栈中;每一次,我们取出一个栈中元素,将其值插入到list中,再将其所有子节点从右往左依次保存到栈中;直到最后的栈为空;
Java
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> result = new ArrayList<>();
Stack<Node> treeNode = new Stack<>();
if (root == null) return result;
treeNode.push(root);
while (!treeNode.isEmpty()) {
Node temp = treeNode.pop();
result.add(temp.val);
for (int i = temp.children.size() - 1; i >= 0; i--) {
treeNode.push(temp.children.get(i));
}
}
return result;
}
}