binary-tree-right-side-view
This commit is contained in:
parent
297be9db08
commit
55d2bb93c9
|
@ -0,0 +1,45 @@
|
||||||
|
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
|
||||||
|
}
|
Loading…
Reference in New Issue