Leetcode - Boundary of Binary Tree
Leetcode - Populating Next Right Pointers in Each Node

Leetcode - Binary Tree Right Side View

violet posted @ Apr 25, 2020 06:16:10 AM in 算法 with tags Algorithm Golang tree , 171 阅读

https://leetcode.com/problems/binary-tree-right-side-view/

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    queue := []*TreeNode{root}
    result := []int{}
    for len(queue) != 0 {
        size := len(queue)
        for i := 0; i < size; i++ {
            node := queue[i]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            if i == size - 1 {
                result = append(result, node.Val)
            }
        }
        queue = queue[size:]
    }
    
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter