forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 06. Extract Leaves of a Binary Tree in a Doubly Linked List.py
- Loading branch information
1 parent
640a1ce
commit 3efdc72
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
06_Binary-Trees/06. Extract Leaves of a Binary Tree in a Doubly Linked List.py
This file contains 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,44 @@ | ||
# https://practice.geeksforgeeks.org/problems/leaves-to-dll/1 | ||
|
||
def convertToDLL(root): | ||
#return the head of the DLL and remove those node from the tree as well. | ||
notLeaves = set() | ||
|
||
def isLeaves(root): | ||
if not root.left and not root.right and root not in notLeaves: return True | ||
return False | ||
|
||
def addToDDL(node): | ||
nonlocal cur | ||
cur.right = node | ||
node.left = cur | ||
cur = cur.right | ||
|
||
dummy = Node(-1) | ||
cur = dummy | ||
|
||
def dfs(root): | ||
nonlocal cur | ||
if not root: return | ||
dfs(root.left) | ||
if root.left and isLeaves(root.left): | ||
node = root.left | ||
root.left = None | ||
addToDDL(node) | ||
notLeaves.add(root) | ||
if root.right and isLeaves(root.right): | ||
node = root.right | ||
root.right = None | ||
addToDDL(node) | ||
notLeaves.add(root) | ||
dfs(root.right) | ||
|
||
dfs(root) | ||
|
||
res = dummy.right | ||
dummy.right = None | ||
res.left = None | ||
|
||
return res | ||
|
||
|