Created
August 13, 2020 23:02
-
-
Save bparanj/d319595ae3fed70dd8451759dd88c244 to your computer and use it in GitHub Desktop.
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
# Definition for a binary tree node. | |
# class TreeNode | |
# attr_accessor :val, :left, :right | |
# def initialize(val = 0, left = nil, right = nil) | |
# @val = val | |
# @left = left | |
# @right = right | |
# end | |
# end | |
# @param {TreeNode} root | |
# @return {Void} Do not return anything, modify root in-place instead. | |
def flatten(node) | |
if node.nil? || (node.left.nil? && node.right.nil?) | |
return | |
end | |
unless node.left.nil? | |
flatten(node.left) | |
right = node.right | |
node.right = node.left | |
node.left = nil | |
current = node.right | |
while current.right | |
current = current.right | |
end | |
current.right = right | |
end | |
unless node.right.nil? | |
flatten(node.right) | |
end | |
return node | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactored version of first solution.