-
-
Notifications
You must be signed in to change notification settings - Fork 155
Binary tree traversal #760
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ajay-dhangar
merged 5 commits into
codeharborhub:main
from
mahek0620:binary-tree-traversal
Jun 9, 2024
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fefeae9
Create 0144-binary-tree-preorder-traversal.md
mahek0620 439fbd2
Create 0145-binary-tree-postorder-traversal.md
mahek0620 5310ca5
Update 0144-binary-tree-preorder-traversal.md
mahek0620 2a3acd2
Update 0144-binary-tree-preorder-traversal.md
mahek0620 78014ce
Update 0145-binary-tree-postorder-traversal.md
mahek0620 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
164 changes: 164 additions & 0 deletions
164
dsa-solutions/lc-solutions/0100-0199/0144-binary-tree-preorder-traversal.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
--- | ||
id: binary tree preorder traversal | ||
title: Binary Tree Preorder Traversal | ||
sidebar_label: 0144 Binary Tree Preorder Traversal | ||
tags: | ||
- tree | ||
- DFS | ||
- LeetCode | ||
- Python | ||
- Java | ||
- C++ | ||
description: "This is a solution to the Binary Tree Preorder Traversal problem on LeetCode." | ||
--- | ||
|
||
## Problem Description | ||
|
||
Given the root of a binary tree, return the preorder traversal of its nodes' values. | ||
|
||
### Examples | ||
|
||
**Example 1:** | ||
|
||
``` | ||
|
||
Input: root = [1,null,2,3] | ||
Output: [1,2,3] | ||
``` | ||
|
||
**Example 2:** | ||
|
||
``` | ||
Input: root = [] | ||
Output: [] | ||
``` | ||
**Example 3:** | ||
|
||
``` | ||
Input: root = [1] | ||
Output: [1] | ||
``` | ||
|
||
### Constraints | ||
|
||
- The number of nodes in the tree is in the range $[0, 100]$. | ||
- $-100 <= Node.val <= 100$ | ||
|
||
|
||
#### Code in Different Languages | ||
|
||
<Tabs> | ||
<TabItem value="Python" label="Python"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```python | ||
# Definition for a binary tree node. | ||
class TreeNode: | ||
def __init__(self, val=0, left=None, right=None): | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
class Solution: | ||
def preorderTraversal(self, root): | ||
if not root: | ||
return [] | ||
result = [] | ||
stack = [root] | ||
while stack: | ||
node = stack.pop() | ||
result.append(node.val) | ||
if node.right: | ||
stack.append(node.right) | ||
if node.left: | ||
stack.append(node.left) | ||
return result | ||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="Java" label="Java"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```java | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Stack; | ||
|
||
// Definition for a binary tree node. | ||
class TreeNode { | ||
int val; | ||
TreeNode left; | ||
TreeNode right; | ||
TreeNode(int x) { val = x; } | ||
} | ||
|
||
class Solution { | ||
public List<Integer> preorderTraversal(TreeNode root) { | ||
List<Integer> result = new ArrayList<>(); | ||
if (root == null) | ||
return result; | ||
Stack<TreeNode> stack = new Stack<>(); | ||
stack.push(root); | ||
while (!stack.isEmpty()) { | ||
TreeNode node = stack.pop(); | ||
result.add(node.val); | ||
if (node.right != null) | ||
stack.push(node.right); | ||
if (node.left != null) | ||
stack.push(node.left); | ||
} | ||
return result; | ||
} | ||
} | ||
|
||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="C++" label="C++"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```cpp | ||
#include <vector> | ||
#include <stack> | ||
using namespace std; | ||
|
||
// Definition for a binary tree node provided by the precompiled header. | ||
struct TreeNode; | ||
|
||
class Solution { | ||
public: | ||
vector<int> preorderTraversal(TreeNode* root) { | ||
if (!root) | ||
return {}; | ||
vector<int> result; | ||
stack<TreeNode*> s; | ||
s.push(root); | ||
while (!s.empty()) { | ||
TreeNode* node = s.top(); | ||
s.pop(); | ||
result.push_back(node->val); | ||
if (node->right) | ||
s.push(node->right); | ||
if (node->left) | ||
s.push(node->left); | ||
} | ||
return result; | ||
} | ||
}; | ||
|
||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
|
||
|
||
## References | ||
|
||
- **LeetCode Problem**: [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | ||
|
||
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/binary-tree-preorder-traversal/solution/) | ||
|
||
- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) |
202 changes: 202 additions & 0 deletions
202
dsa-solutions/lc-solutions/0100-0199/0145-binary-tree-postorder-traversal.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
--- | ||
id: binary-tree-postorder-traversal | ||
title: Binary-Tree-Postorder-Traversal | ||
sidebar_label: 0145 Binary-Tree-Postorder-Traversal | ||
tags: | ||
- DFS | ||
- LeetCode | ||
- Java | ||
- Python | ||
- C++ | ||
description: "This is a solution to the Binary-Tree-Postorder-Traversal problem on LeetCode." | ||
--- | ||
|
||
## Problem Description | ||
|
||
Given the root of a binary tree, return the postorder traversal of its nodes' values. | ||
|
||
### Examples | ||
|
||
**Example 1:** | ||
|
||
``` | ||
|
||
|
||
Input: root = [1,null,2,3] | ||
Output: [3,2,1] | ||
|
||
``` | ||
|
||
**Example 2:** | ||
|
||
|
||
``` | ||
Input: root = [] | ||
Output: [] | ||
``` | ||
|
||
**Example 3:** | ||
|
||
|
||
``` | ||
Input: root = [1] | ||
Output: [1] | ||
``` | ||
|
||
|
||
### Constraints | ||
|
||
- The number of the nodes in the tree is in the range [0, 100] | ||
- $-100 <= Node.val <= 100$ | ||
|
||
|
||
--- | ||
|
||
## Solution for Binary-Tree-Postorder-Traversal Problem | ||
|
||
### Intuition | ||
|
||
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. | ||
|
||
|
||
### Approach | ||
|
||
### Recursive Approach (DFS - Depth First Search): | ||
|
||
- Perform postorder traversal recursively by visiting the left subtree, then the right subtree, and finally the root node. | ||
- Base case: If the current node is null, return. | ||
- Recursively call the function on the left subtree. | ||
- Recursively call the function on the right subtree. | ||
- Append the value of the current node to the result list. | ||
- Return the result list. | ||
|
||
### Iterative Approach (Using Stack): | ||
|
||
- Start from the root node and initialize an empty stack. | ||
- While the stack is not empty or the current node is not null: | ||
- Traverse down the left subtree until you reach a leaf node, pushing each node onto the stack. | ||
- Once you reach a leaf node, pop the top node from the stack. | ||
- 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. | ||
- 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. | ||
- Return the result list. | ||
|
||
|
||
|
||
#### Code in Different Languages | ||
|
||
<Tabs> | ||
<TabItem value="Python" label="Python"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```python | ||
# Definition for a binary tree node. | ||
class TreeNode: | ||
def __init__(self, val=0, left=None, right=None): | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
class Solution: | ||
def postorderTraversal(self, root): | ||
if not root: | ||
return [] | ||
result = [] | ||
stack = [root] | ||
while stack: | ||
node = stack.pop() | ||
result.append(node.val) | ||
if node.left: | ||
stack.append(node.left) | ||
if node.right: | ||
stack.append(node.right) | ||
return result[::-1] | ||
|
||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="Java" label="Java"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```java | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Stack; | ||
|
||
// Definition for a binary tree node. | ||
class TreeNode { | ||
int val; | ||
TreeNode left; | ||
TreeNode right; | ||
TreeNode(int x) { val = x; } | ||
} | ||
|
||
class Solution { | ||
public List<Integer> postorderTraversal(TreeNode root) { | ||
List<Integer> result = new ArrayList<>(); | ||
if (root == null) | ||
return result; | ||
Stack<TreeNode> stack = new Stack<>(); | ||
stack.push(root); | ||
while (!stack.isEmpty()) { | ||
TreeNode node = stack.pop(); | ||
result.add(0, node.val); // Insert node.val at the beginning of the result list | ||
if (node.left != null) | ||
stack.push(node.left); | ||
if (node.right != null) | ||
stack.push(node.right); | ||
} | ||
return result; | ||
} | ||
} | ||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="C++" label="C++"> | ||
<SolutionAuthor name="@mahek0620"/> | ||
```cpp | ||
#include <vector> | ||
#include <stack> | ||
using namespace std; | ||
|
||
// Definition for a binary tree node provided by the precompiled header. | ||
struct TreeNode; | ||
|
||
class Solution { | ||
public: | ||
vector<int> postorderTraversal(TreeNode* root) { | ||
if (!root) | ||
return {}; | ||
vector<int> result; | ||
stack<TreeNode*> s; | ||
s.push(root); | ||
while (!s.empty()) { | ||
TreeNode* node = s.top(); | ||
s.pop(); | ||
result.push_back(node->val); | ||
if (node->left) | ||
s.push(node->left); | ||
if (node->right) | ||
s.push(node->right); | ||
} | ||
reverse(result.begin(), result.end()); | ||
return result; | ||
} | ||
}; | ||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
|
||
|
||
## References | ||
|
||
- **LeetCode Problem:** [Binary-Tree-Postorder-Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | ||
- **Solution Link:** [Binary-Tree-Postorder-Traversal Solution on LeetCode](https://leetcode.com/problems/binary-tree-postorder-traversal/solutions/5273312/binary-tree-postorder-traversal-solution) | ||
- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.