The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The height of the n-ary tree is less than or equal to 1000.
Follow up: Recursive solution is trivial, could you do it iteratively?
Solutions
Solution 1: Recursion
Thinking
N-ary preorder is the root, then children from left to right. Recursion matches the definition.
Append the root, then recurse on each child. An empty tree yields an empty list. Each node is visited once.
We can recursively traverse the entire tree. For each node, we first add the node's value to the answer, then recursively call the function for each of the node's children.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes.
1 2 3 4 5 6 7 8 9101112131415161718192021
"""# Definition for a Node.class Node: def __init__(self, val=None, children=None): self.val = val self.children = children"""classSolution:defpreorder(self,root:"Node")->List[int]:defdfs(root):ifrootisNone:returnans.append(root.val)forchildinroot.children:dfs(child)ans=[]dfs(root)returnans
/*// Definition for a Node.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; }};*/classSolution{privateList<Integer>ans=newArrayList<>();publicList<Integer>preorder(Noderoot){dfs(root);returnans;}privatevoiddfs(Noderoot){if(root==null){return;}ans.add(root.val);for(Nodechild:root.children){dfs(child);}}}
/*// 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; }};*/classSolution{public:vector<int>preorder(Node*root){vector<int>ans;function<void(Node*)>dfs=[&](Node*root){if(!root){return;}ans.push_back(root->val);for(auto&child:root->children){dfs(child);}};dfs(root);returnans;}};
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcpreorder(root*Node)(ans[]int){vardfsfunc(*Node)dfs=func(root*Node){ifroot==nil{return}ans=append(ans,root.Val)for_,child:=rangeroot.Children{dfs(child)}}dfs(root)return}
/** * Definition for a Node. * struct Node { * int val; * int numChildren; * struct Node** children; * }; *//** * Note: The returned array must be malloced, assume caller calls free(). */voiddfs(structNode*root,int*ans,int*i){if(!root){return;}ans[(*i)++]=root->val;for(intj=0;j<root->numChildren;j++){dfs(root->children[j],ans,i);}}int*preorder(structNode*root,int*returnSize){int*ans=malloc(sizeof(int)*10000);*returnSize=0;dfs(root,ans,returnSize);returnans;}
Solution 2: Iteration (Stack Implementation)
Thinking
Solution 1 already walks preorder with an explicit stack, pushing children from right to left so the leftmost child pops first.
This section is the same walk. Pop a node, record it, then push its children in reverse. The order matches the preorder definition.
This section uses the same explicit stack.
We use a stack to help us get the pre-order traversal. We first push the root node into the stack. Since the pre-order traversal is root, left subtree, right subtree, and the characteristic of the stack is first in last out, we first add the node's value to the answer, then push each of the node's children into the stack in the order from right to left. We continue this process until the stack is empty.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes.
1 2 3 4 5 6 7 8 9101112131415161718192021
"""# Definition for a Node.class Node: def __init__(self, val=None, children=None): self.val = val self.children = children"""classSolution:defpreorder(self,root:'Node')->List[int]:ans=[]ifrootisNone:returnansstk=[root]whilestk:node=stk.pop()ans.append(node.val)forchildinnode.children[::-1]:stk.append(child)returnans
/*// Definition for a Node.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; }};*/classSolution{publicList<Integer>preorder(Noderoot){if(root==null){returnCollections.emptyList();}List<Integer>ans=newArrayList<>();Deque<Node>stk=newArrayDeque<>();stk.push(root);while(!stk.isEmpty()){Nodenode=stk.pop();ans.add(node.val);List<Node>children=node.children;for(inti=children.size()-1;i>=0;--i){stk.push(children.get(i));}}returnans;}}
/*// 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; }};*/classSolution{public:vector<int>preorder(Node*root){if(!root)return{};vector<int>ans;stack<Node*>stk;stk.push(root);while(!stk.empty()){Node*node=stk.top();ans.push_back(node->val);stk.pop();autochildren=node->children;for(inti=children.size()-1;i>=0;--i)stk.push(children[i]);}returnans;}};
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcpreorder(root*Node)(ans[]int){ifroot==nil{return}stk:=[]*Node{root}forlen(stk)>0{node:=stk[len(stk)-1]ans=append(ans,node.Val)stk=stk[:len(stk)-1]children:=node.Childrenfori:=len(children)-1;i>=0;i--{stk=append(stk,children[i])}}return}
N-ary preorder records the root, then the children from left to right. Recursion on a chain of height \(1000\) exhausts the call stack, and \(1000\) is the height limit.
The bottleneck is that chain: each call steps into the single next child, so the depth tracks the height.
Preorder records the current node before visiting children, so the walk does not wait for a child to return.
An explicit stack holds the nodes still to visit. Pop a node, append its value, then push its children from right to left so the leftmost child pops first. An empty tree returns an empty list.
Simulate preorder with a stack. Push the root, and after popping a node append its value, then push its children from right to left until the stack is empty.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes.
1 2 3 4 5 6 7 8 9101112131415161718192021
"""# Definition for a Node.class Node: def __init__(self, val=None, children=None): self.val = val self.children = children"""classSolution:defpreorder(self,root:'Node')->List[int]:ans=[]ifrootisNone:returnansstk=[root]whilestk:node=stk.pop()ans.append(node.val)forchildinnode.children[::-1]:stk.append(child)returnans
/*// Definition for a Node.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; }};*/classSolution{publicList<Integer>preorder(Noderoot){if(root==null){returnCollections.emptyList();}List<Integer>ans=newArrayList<>();Deque<Node>stk=newArrayDeque<>();stk.push(root);while(!stk.isEmpty()){Nodenode=stk.pop();ans.add(node.val);List<Node>children=node.children;for(inti=children.size()-1;i>=0;--i){stk.push(children.get(i));}}returnans;}}
/*// 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; }};*/classSolution{public:vector<int>preorder(Node*root){if(!root)return{};vector<int>ans;stack<Node*>stk;stk.push(root);while(!stk.empty()){Node*node=stk.top();ans.push_back(node->val);stk.pop();autochildren=node->children;for(inti=children.size()-1;i>=0;--i)stk.push(children[i]);}returnans;}};
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcpreorder(root*Node)(ans[]int){ifroot==nil{return}stk:=[]*Node{root}forlen(stk)>0{node:=stk[len(stk)-1]ans=append(ans,node.Val)stk=stk[:len(stk)-1]children:=node.Childrenfori:=len(children)-1;i>=0;i--{stk=append(stk,children[i])}}return}
/** * Definition for a Node. * struct Node { * int val; * int numChildren; * struct Node** children; * }; *//** * Note: The returned array must be malloced, assume caller calls free(). */int*preorder(structNode*root,int*returnSize){int*ans=malloc(sizeof(int)*10000);*returnSize=0;if(!root){returnans;}structNode**stk=malloc(sizeof(structNode*)*10000);inttop=0;stk[top++]=root;while(top){structNode*node=stk[--top];ans[(*returnSize)++]=node->val;for(intj=node->numChildren-1;j>=0;--j){stk[top++]=node->children[j];}}free(stk);returnans;}