【Binary tree】Right view of binary tree

0x00 topic

Given the root node of a binary tree, root
imagine yourself standing on it, 右侧
in order from part to part
Return the value of the node that can be seen from the right


0x01 Ideas

Equivalent to each layer, only 最右边the can be traversed
by using the method to obtain all the nodes of the current layer and save the last node层序


0x02 solution

language:Swift

tree node:TreeNode

public class TreeNode {
    public var val: Int
    public var left: TreeNode?
    public var right: TreeNode?
    public init() { self.val = 0; self.left = nil; self.right = nil; }
    public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
    public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
        self.val = val
        self.left = left
        self.right = right
    }
}

solution:

func rightSideView(_ root: TreeNode?) -> [Int] {
    guard let r = root else { return [] }
    
    // 保存结果 
    var res: [Int] = []
    
    // 存储每一层的节点
    var queue: [TreeNode] = []
    queue.append(r)

    while (!queue.isEmpty) {
        // 获取最后一个,保存
        let node = queue.last!
        res.append(node.val)

		// 获取下一层的所有节点
        var tmp: [TreeNode] = []
        for n in queue {
            if let left = n.left {
                tmp.append(left)
            }
            if let right = n.right {
                tmp.append(right)
            }
        }
        
        // 切换到下一层
        queue = tmp
    }
    
	// 返回结果  
    return res
}


applet application

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/123097128