leet-code/binary-tree-right-side-view/sol.go

46 lines
908 B
Go
Raw Normal View History

2022-07-11 20:03:55 +00:00
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) (out []int) {
if root == nil {
return
}
for stack := []*TreeNode{root}; len(stack) != 0; {
top := stack[len(stack)-1]
if len(stack) > len(out) {
out = append(out, top.Val)
}
if top.Right != nil {
stack = append(stack, top.Right)
} else if top.Left != nil {
stack = append(stack, top.Left)
} else {
stack = stack[:len(stack)-1]
if len(stack) != 0 {
new_top := stack[len(stack)-1]
// Easiest way to DFS by modification of tree.
// There was no requirement to keep it intact ¯\_(ツ)_/¯.
if new_top.Right == top {
new_top.Right = nil
} else {
new_top.Left = nil
}
}
}
}
return
}