Right view of binary tree--Shensou

0x01. Question

Given a binary tree, imagine yourself standing on the right side of it, returning the node values ​​that can be seen from the right side, in order 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.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 public List<Integer> rightSideView(TreeNode root)

0x02. Brief analysis

Observe the problem. The problem is easier to understand. The binary tree node seen in the right view is the first node seen from the right.

Although the problem is easier to understand, if you really do it right away, you will find that there are more special cases, which shows that we are not thinking about the best way.

First of all, it is perfectly possible to use deep search. The key is to find out how to find the rightmost node.

If we think about it again, we can find a feature. These nodes are the rightmost nodes in each layer of the binary tree.

  • If we go to the right node every time during the deep search, then when accessing a certain layer, the first node must be the rightmost node, and then stored in a hash table There is a node in this layer, then no longer join the hash table.
  • Since this view is related to the depth of the binary tree, a maximum depth needs to be maintained and a real-time stack is required.

0x03. Solve the code-deep search (stack)


class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        Map<Integer,Integer> rightMaxDepth=new HashMap<>();
        int maxDepth=-1;
        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> depthStack = new Stack<>();
        nodeStack.push(root);
        depthStack.push(0);
        while(!nodeStack.isEmpty()){
            TreeNode node=nodeStack.pop();
            int depth=depthStack.pop();
            if(node!=null){
                maxDepth=Math.max(maxDepth,depth);
                if(!rightMaxDepth.containsKey(depth)){
                    rightMaxDepth.put(depth,node.val);
                }
                nodeStack.push(node.left);
                nodeStack.push(node.right);
                depthStack.push(depth+1);
                depthStack.push(depth+1);
            }
        }
        List<Integer> rightView=new ArrayList<>();
        for(int i=0;i<=maxDepth;i++){
            rightView.add(rightMaxDepth.get(i));
        }
        return rightView;
    }

}

ATFWUS --Writing By 2020–04-22

Published 210 original articles · Like 239 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/ATFWUS/article/details/105673310