leetcode刷题笔记 一百九十九题 二叉树的右视图

leetcode刷题笔记 一百九十九题 二叉树的右视图

源地址:199. 二叉树的右视图

问题描述:

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

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

//基于DFS的递归方法 优先右侧
/**
 * Definition for a binary tree node.
 * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
 *   var value: Int = _value
 *   var left: TreeNode = _left
 *   var right: TreeNode = _right
 * }
 */
//DFS 递归
import scala.collection.mutable
object Solution {
    def rightSideView(root: TreeNode): List[Int] = {
        val res = new mutable.ListBuffer[Int]()
        
        def dfs(root: TreeNode, depth: Int): Unit = {
            if (root == null) return
            if (depth == res.size) res.append(root.value)
            dfs(root.right, depth+1)
            dfs(root.left, depth+1)
        }
        
        dfs(root, 0)
        return res.toList
    }
}

//BFS 逐层遍历 取每层最后侧节点
/**
 * Definition for a binary tree node.
 * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
 *   var value: Int = _value
 *   var left: TreeNode = _left
 *   var right: TreeNode = _right
 * }
 */
//BFS
import scala.collection.mutable
object Solution {
    def rightSideView(root: TreeNode): List[Int] = {
        val res = new mutable.ListBuffer[Int]()
        if (root == null) return res.toList
        
        val queue = new mutable.Queue[TreeNode]()
        queue.enqueue(root)
        while (queue.isEmpty == false){
            val size = queue.size
            for(i <- 0 to size-1){
                val node = queue.dequeue
                if (node.left != null) queue.enqueue(node.left)
                if (node.right != null) queue.enqueue(node.right)
                if (i == size-1) res.append(node.value)
            }
        }
        return res.toList
    }
}
posted @ 2020-09-19 14:21  ganshuoos  阅读(88)  评论(0编辑  收藏  举报