Skip to content

Commit 611b28c

Browse files
authored
Merge pull request #760 from mahek0620/binary-tree-traversal
Binary tree traversal
2 parents 1f71cc7 + 78014ce commit 611b28c

File tree

2 files changed

+366
-0
lines changed

2 files changed

+366
-0
lines changed
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
---
2+
id: binary tree preorder traversal
3+
title: Binary Tree Preorder Traversal
4+
sidebar_label: 0144 Binary Tree Preorder Traversal
5+
tags:
6+
- tree
7+
- DFS
8+
- LeetCode
9+
- Python
10+
- Java
11+
- C++
12+
description: "This is a solution to the Binary Tree Preorder Traversal problem on LeetCode."
13+
---
14+
15+
## Problem Description
16+
17+
Given the root of a binary tree, return the preorder traversal of its nodes' values.
18+
19+
### Examples
20+
21+
**Example 1:**
22+
23+
```
24+
25+
Input: root = [1,null,2,3]
26+
Output: [1,2,3]
27+
```
28+
29+
**Example 2:**
30+
31+
```
32+
Input: root = []
33+
Output: []
34+
```
35+
**Example 3:**
36+
37+
```
38+
Input: root = [1]
39+
Output: [1]
40+
```
41+
42+
### Constraints
43+
44+
- The number of nodes in the tree is in the range $[0, 100]$.
45+
- $-100 <= Node.val <= 100$
46+
47+
48+
#### Code in Different Languages
49+
50+
<Tabs>
51+
<TabItem value="Python" label="Python">
52+
<SolutionAuthor name="@mahek0620"/>
53+
```python
54+
# Definition for a binary tree node.
55+
class TreeNode:
56+
def __init__(self, val=0, left=None, right=None):
57+
self.val = val
58+
self.left = left
59+
self.right = right
60+
61+
class Solution:
62+
def preorderTraversal(self, root):
63+
if not root:
64+
return []
65+
result = []
66+
stack = [root]
67+
while stack:
68+
node = stack.pop()
69+
result.append(node.val)
70+
if node.right:
71+
stack.append(node.right)
72+
if node.left:
73+
stack.append(node.left)
74+
return result
75+
76+
```
77+
78+
</TabItem>
79+
<TabItem value="Java" label="Java">
80+
<SolutionAuthor name="@mahek0620"/>
81+
```java
82+
import java.util.ArrayList;
83+
import java.util.List;
84+
import java.util.Stack;
85+
86+
// Definition for a binary tree node.
87+
class TreeNode {
88+
int val;
89+
TreeNode left;
90+
TreeNode right;
91+
TreeNode(int x) { val = x; }
92+
}
93+
94+
class Solution {
95+
public List<Integer> preorderTraversal(TreeNode root) {
96+
List<Integer> result = new ArrayList<>();
97+
if (root == null)
98+
return result;
99+
Stack<TreeNode> stack = new Stack<>();
100+
stack.push(root);
101+
while (!stack.isEmpty()) {
102+
TreeNode node = stack.pop();
103+
result.add(node.val);
104+
if (node.right != null)
105+
stack.push(node.right);
106+
if (node.left != null)
107+
stack.push(node.left);
108+
}
109+
return result;
110+
}
111+
}
112+
113+
114+
115+
```
116+
117+
</TabItem>
118+
<TabItem value="C++" label="C++">
119+
<SolutionAuthor name="@mahek0620"/>
120+
```cpp
121+
#include <vector>
122+
#include <stack>
123+
using namespace std;
124+
125+
// Definition for a binary tree node provided by the precompiled header.
126+
struct TreeNode;
127+
128+
class Solution {
129+
public:
130+
vector<int> preorderTraversal(TreeNode* root) {
131+
if (!root)
132+
return {};
133+
vector<int> result;
134+
stack<TreeNode*> s;
135+
s.push(root);
136+
while (!s.empty()) {
137+
TreeNode* node = s.top();
138+
s.pop();
139+
result.push_back(node->val);
140+
if (node->right)
141+
s.push(node->right);
142+
if (node->left)
143+
s.push(node->left);
144+
}
145+
return result;
146+
}
147+
};
148+
149+
150+
151+
```
152+
153+
</TabItem>
154+
</Tabs>
155+
156+
157+
158+
## References
159+
160+
- **LeetCode Problem**: [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)
161+
162+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/binary-tree-preorder-traversal/solution/)
163+
164+
- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
---
2+
id: binary-tree-postorder-traversal
3+
title: Binary-Tree-Postorder-Traversal
4+
sidebar_label: 0145 Binary-Tree-Postorder-Traversal
5+
tags:
6+
- DFS
7+
- LeetCode
8+
- Java
9+
- Python
10+
- C++
11+
description: "This is a solution to the Binary-Tree-Postorder-Traversal problem on LeetCode."
12+
---
13+
14+
## Problem Description
15+
16+
Given the root of a binary tree, return the postorder traversal of its nodes' values.
17+
18+
### Examples
19+
20+
**Example 1:**
21+
22+
```
23+
24+
25+
Input: root = [1,null,2,3]
26+
Output: [3,2,1]
27+
28+
```
29+
30+
**Example 2:**
31+
32+
33+
```
34+
Input: root = []
35+
Output: []
36+
```
37+
38+
**Example 3:**
39+
40+
41+
```
42+
Input: root = [1]
43+
Output: [1]
44+
```
45+
46+
47+
### Constraints
48+
49+
- The number of the nodes in the tree is in the range [0, 100]
50+
- $-100 <= Node.val <= 100$
51+
52+
53+
---
54+
55+
## Solution for Binary-Tree-Postorder-Traversal Problem
56+
57+
### Intuition
58+
59+
Imagine walking through the tree in a clockwise direction, starting from the left subtree, then moving to the right subtree, and finally reaching the root node. At each step, you collect the values of the nodes you visit, following the order: left, right, root.
60+
61+
62+
### Approach
63+
64+
### Recursive Approach (DFS - Depth First Search):
65+
66+
- Perform postorder traversal recursively by visiting the left subtree, then the right subtree, and finally the root node.
67+
- Base case: If the current node is null, return.
68+
- Recursively call the function on the left subtree.
69+
- Recursively call the function on the right subtree.
70+
- Append the value of the current node to the result list.
71+
- Return the result list.
72+
73+
### Iterative Approach (Using Stack):
74+
75+
- Start from the root node and initialize an empty stack.
76+
- While the stack is not empty or the current node is not null:
77+
- Traverse down the left subtree until you reach a leaf node, pushing each node onto the stack.
78+
- Once you reach a leaf node, pop the top node from the stack.
79+
- If the popped node has a right child and it is equal to the top of the stack, it means the right subtree has not been visited yet. In this case, pop the top node again and push the popped node back onto the stack, then move to its right child.
80+
- If the popped node does not have a right child or its right child has already been visited, append its value to the result list.
81+
- Return the result list.
82+
83+
84+
85+
#### Code in Different Languages
86+
87+
<Tabs>
88+
<TabItem value="Python" label="Python">
89+
<SolutionAuthor name="@mahek0620"/>
90+
```python
91+
# Definition for a binary tree node.
92+
class TreeNode:
93+
def __init__(self, val=0, left=None, right=None):
94+
self.val = val
95+
self.left = left
96+
self.right = right
97+
98+
class Solution:
99+
def postorderTraversal(self, root):
100+
if not root:
101+
return []
102+
result = []
103+
stack = [root]
104+
while stack:
105+
node = stack.pop()
106+
result.append(node.val)
107+
if node.left:
108+
stack.append(node.left)
109+
if node.right:
110+
stack.append(node.right)
111+
return result[::-1]
112+
113+
114+
115+
```
116+
117+
</TabItem>
118+
<TabItem value="Java" label="Java">
119+
<SolutionAuthor name="@mahek0620"/>
120+
```java
121+
import java.util.ArrayList;
122+
import java.util.List;
123+
import java.util.Stack;
124+
125+
// Definition for a binary tree node.
126+
class TreeNode {
127+
int val;
128+
TreeNode left;
129+
TreeNode right;
130+
TreeNode(int x) { val = x; }
131+
}
132+
133+
class Solution {
134+
public List<Integer> postorderTraversal(TreeNode root) {
135+
List<Integer> result = new ArrayList<>();
136+
if (root == null)
137+
return result;
138+
Stack<TreeNode> stack = new Stack<>();
139+
stack.push(root);
140+
while (!stack.isEmpty()) {
141+
TreeNode node = stack.pop();
142+
result.add(0, node.val); // Insert node.val at the beginning of the result list
143+
if (node.left != null)
144+
stack.push(node.left);
145+
if (node.right != null)
146+
stack.push(node.right);
147+
}
148+
return result;
149+
}
150+
}
151+
152+
153+
```
154+
155+
</TabItem>
156+
<TabItem value="C++" label="C++">
157+
<SolutionAuthor name="@mahek0620"/>
158+
```cpp
159+
#include <vector>
160+
#include <stack>
161+
using namespace std;
162+
163+
// Definition for a binary tree node provided by the precompiled header.
164+
struct TreeNode;
165+
166+
class Solution {
167+
public:
168+
vector<int> postorderTraversal(TreeNode* root) {
169+
if (!root)
170+
return {};
171+
vector<int> result;
172+
stack<TreeNode*> s;
173+
s.push(root);
174+
while (!s.empty()) {
175+
TreeNode* node = s.top();
176+
s.pop();
177+
result.push_back(node->val);
178+
if (node->left)
179+
s.push(node->left);
180+
if (node->right)
181+
s.push(node->right);
182+
}
183+
reverse(result.begin(), result.end());
184+
return result;
185+
}
186+
};
187+
188+
189+
```
190+
191+
</TabItem>
192+
</Tabs>
193+
194+
195+
196+
197+
198+
## References
199+
200+
- **LeetCode Problem:** [Binary-Tree-Postorder-Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)
201+
- **Solution Link:** [Binary-Tree-Postorder-Traversal Solution on LeetCode](https://leetcode.com/problems/binary-tree-postorder-traversal/solutions/5273312/binary-tree-postorder-traversal-solution)
202+
- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)

0 commit comments

Comments
 (0)