[B] [C] [D]

Given the root node of a binary tree, root, imagine yourself standing on the right side of it and returning the values of the nodes visible from the right side, in order from top to bottom.

Example 1:

Input: [1,3, null,5,null,4] output: [1,3,4]Copy the code

Example 2:

Input: [1, NULL,3] Output: [1,3]Copy the code

Example 3:

Input: [] Output: []Copy the code

Tip:

  • The number of nodes in the binary tree is in the range[0100]
  • -100 <= Node.val <= 100

Their thinking

In this case, the right view to obtain is actually the value of the rightmost node of each layer, so we need to perform sequential traversal and obtain the value of the rightmost node of each layer. Here, we can use pre-order traversal or middle-order traversal, as long as the right subtree is the last traversal. During the traversal process, the depth of the current node is recorded, and the current node value is assigned to the corresponding subscript element of the result array. Because it is the right subtree to be processed last, the value of the subscript position in the last array is the value of the rightmost node of the current layer.

Code implementation

Var rightSideView = function(root) {const res = []; Function preorder(node,deep){if(node === null) return; Res [deep] = node.val; Preorder (node. Left,deep+1); Preorder (node.right,deep+1); } preorder(root,0); // return result array return res; };Copy the code

This completes the right view of the Leetcode-199-binary tree

If you have any questions or suggestions, please leave a comment!