Skip to content

Commit b56e2d2

Browse files
committed
added N-ary Tree Postorder Traversal (easy)
1 parent a576f3e commit b56e2d2

File tree

5 files changed

+62
-0
lines changed

5 files changed

+62
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
# N-ary Tree Postorder Traversal
3+
[Leetcode Link](https://leetcode.com/problems/n-ary-tree-postorder-traversal/)
4+
5+
## Problem:
6+
7+
Given an n-ary tree, return the *postorder* traversal of its nodes' values.
8+
9+
*Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).*
10+
11+
**Follow up:**
12+
13+
Recursive solution is trivial, could you do it iteratively?
14+
15+
## Example:
16+
17+
![example](assets/narytreeexample.png)
18+
```
19+
Input: root = [1,null,3,2,4,null,5,6]
20+
Output: [5,6,3,2,4,1]
21+
```
22+
![example](assets/narytreeexample2.png)
23+
```
24+
Input: 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]
25+
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
26+
```
27+
28+
## Note:
29+
30+
- The height of the n-ary tree is less than or equal to `1000`
31+
- The total number of nodes is between `[0, 10^4]`
30 KB
Loading
30.7 KB
Loading
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
# Definition for a Node.
4+
class Node:
5+
def __init__(self, val=None, children=None):
6+
self.val = val
7+
self.children = children
8+
9+
def __repr__(self):
10+
return str(self.val)
11+
12+
class Solution:
13+
def postorder(self, root: 'Node') -> List[int]:
14+
if root is None:
15+
return []
16+
postOrder = list()
17+
stack = list()
18+
stack.append(root)
19+
while stack:
20+
currentNode = stack.pop()
21+
if currentNode.children is not None:
22+
stack.extend(currentNode.children)
23+
postOrder.insert(0, currentNode.val)
24+
return postOrder
25+
26+
27+
# test driver
28+
sol = Solution()
29+
tree = Node(1, [Node(3, [Node(5), Node(6)]), Node(2), Node(4)])
30+
print("Output:", sol.postorder(tree))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Languages used: Java and Python
4242
- [Happy Number](Easy/HappyNumber)
4343
- [Assign Cookies](Easy/AssignCookies)
4444
- [Rotate Array](Easy/RotateArray)
45+
- [N-ary Tree Postorder Traversal](Easy/NaryTreePostorderTraversal)
4546
- Medium
4647
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
4748
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)