https://github.com/emahtab/flatten-binary-tree-to-linked-list
Flatten a Binary Tree to Linked List
https://github.com/emahtab/flatten-binary-tree-to-linked-list
flatten flatten-binary-tree leetcode preorder problem-solving
Last synced: 6 months ago
JSON representation
Flatten a Binary Tree to Linked List
- Host: GitHub
- URL: https://github.com/emahtab/flatten-binary-tree-to-linked-list
- Owner: eMahtab
- Created: 2020-02-08T05:42:19.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-02-08T05:53:41.000Z (over 6 years ago)
- Last Synced: 2025-06-11T02:50:57.214Z (about 1 year ago)
- Topics: flatten, flatten-binary-tree, leetcode, preorder, problem-solving
- Size: 4.88 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Flatten a Binary Tree to Linked List
## https://leetcode.com/problems/flatten-binary-tree-to-linked-list
Given a binary tree, flatten it to a linked list in-place.
```
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
```
# Implementation :
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if(root == null)
return;
Stack stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode current = stack.pop();
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
if(!stack.isEmpty())
current.right = stack.peek();
current.left = null;
}
}
}
```
### ❗️ 💥 Caution : EmptyStackException
Calling `stack.pop()` or `stack.peek()` on an empty stack will result in a EmptyStackException. So always make sure you don't call those method on an empty stack. In above implementation when there is only one `TreeNode` in the stack and we pop it, and the popped TreeNode doesn't have right and left child, so now there will be nothing in the stack, so calling `stack.peek()` will result in EmptyStackException. So we add the check of, if the stack is not empty, then only we call `stack.peek()`.
# References :
https://www.youtube.com/watch?v=vssbwPkarPQ