Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 13, 2020 08:53
Show Gist options
  • Save alldroll/4b3850f6701af9d741435733c9365ecb to your computer and use it in GitHub Desktop.
Save alldroll/4b3850f6701af9d741435733c9365ecb to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/flatten-binary-tree-to-linked-list
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
stack := []*TreeNode{}
for root != nil {
if root.Right != nil {
stack = append(stack, root.Right)
}
if root.Left != nil {
stack = append(stack, root.Left)
}
root.Left = nil
if len(stack) > 0 {
top := stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
root.Right = top
root = top
} else {
root = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment