binary-tree-right-side-view

This commit is contained in:
Gleb Koval 2022-07-11 21:03:55 +01:00
parent 297be9db08
commit 55d2bb93c9
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 45 additions and 0 deletions

View File

@ -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
}