leetcode_987. Vertical traversal of binary tree -- leetcode's way to brush questions

Posted by Stopofeger on Sat, 01 Jan 2022 16:28:42 +0100

Title Description

Give you the root node of the binary tree, root. Please design an algorithm to calculate the vertical traversal sequence of the binary tree.

For each node located in (row, col), its left and right child nodes are located in (row + 1, col - 1) and (row + 1, col + 1). The root node of the tree is located at (0, 0).

The vertical traversal of the binary tree starts from the leftmost column to the end of the rightmost column. All nodes on each column are indexed by column to form an ordered list sorted from top to bottom according to the occurrence position. If there are multiple nodes in the same row and column, the nodes are sorted from small to large.

Returns the vertical traversal sequence of a binary tree.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9], [3,15], [20], [7]]

Explanation:

Column - 1: only node 9 is in this column.
Column 0: only nodes 3 and 15 are in this column, in order from top to bottom.
Column 1: only node 20 is in this column.
Column 2: only node 7 is in this column.

Example 2:

Input: root = [1,2,3,4,5,6,7]
Output: [[4], [2], [1,5,6], [3], [7]]

Explanation:

Column - 2: only node 4 is in this column.
Column - 1: only node 2 is in this column.
Column 0: nodes 1, 5 and 6 are all in this column. 1 is above, so it appears in front. The positions of 5 and 6 are (2, 0), so they are sorted from small to large, and 5 is in front of 6.
Column 1: only node 3 is in this column.
Column 2: only node 7 is in this column.

Example 3:

Input: root = [1,2,3,4,6,5,7]
Output: [[4], [2], [1,5,6], [3], [7]]

Explanation:

This example is actually exactly the same as example 2, except that the positions of nodes 5 and 6 in the tree are exchanged. Because 5 and 6
The position of is still the same, so the answers remain the same and are still sorted from small to large.

Tips:

The total number of nodes in the tree is within the range [1, 1000]
0 <= Node.val <= 1000

Source: LeetCode

General idea of the topic

Traverse a binary tree in vertical order from left to right in the column direction and from right to left in the row direction. If there are several nodes with the same row and column, from large to small
Input: a binary tree
Output: arranged binary tree list < list < Integer '> >

Train of thought description

First, all node coordinates and values should be recorded, then each node should be sorted by y coordinate - > x coordinate - > Val value, and the ordered nodes should be recorded in the List
Available steps:

  1. Create a class myNode and record the values of row, col and val
  2. Traverse all node value records in order to become myNode values
  3. Create an ArrayList < myNode '> mynodelist and store all myNode values in the
  4. Create a user-defined sort, so that the sorting process is arranged in the priority order of y coordinate - > x coordinate - > Val value, with the small one in the front
  5. Sort the list in a custom sort
  6. Store the value of myNodeList in rlist in * * list < list < Integer '> > * * format
  7. Output rlist

code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
		  	List<List<Integer>> rlist=new LinkedList<List<Integer>>();
		  	
		  	ArrayList<myNode> myNodeList=new ArrayList<>();
		  	
		    public List<List<Integer>> verticalTraversal(TreeNode root) {
		    	dfs(0,0,root);

				// 4. Create a user-defined sort, and arrange the sorting process in the priority order of y coordinate - > x coordinate - > Val value, with the small one in the front
		    	//Custom sorting method
		    	Collections.sort(myNodeList,new Comparator<myNode>(){
					
					// 5. Sort the list in a user-defined way
					@Override
					public int compare(myNode o1, myNode o2) {
						// TODO Auto-generated method stub
						if(o1.y!=o2.y){
							return o1.y-o2.y;
						}
						else if(o1.x!=o2.x){
							return o1.x-o2.x;
						}
						else{
                            return o1.val-o2.val;
                        }
						
					}
		    		
		    	});
		    	
               
		    	
		    	//6. Store the value of myNodeList in rlist as list < list < integer > >
		    	//Here, the value is stored in the list first because you need to use the getLast() method in the LinkedList
		    	LinkedList<LinkedList<Integer>> list=new LinkedList<>();
		    	list.add(new LinkedList<Integer>());
		    	
		    	//Initialize and assign the first value of the sorted ArrayList to current
		    	int currentY=myNodeList.get(0).y;
		    	
		    	for(myNode i:myNodeList){
		    		//Because it's sorted,
		    		//If the number of columns is equal, a value is added to the current column
		    		//If the inequality indicates that this row has passed, create a new row
		    		if(currentY!=i.y){
		    			list.add(new LinkedList<Integer>());
		    			currentY=i.y;
		    		}
		    		list.getLast().add(i.val);
		    	}
		    	//7. Output rlist
		    	rlist.addAll(list);
		    	return rlist;

		    }
		    
		    
		    //2. Traverse all node value records in order to become myNode values
		    //3. Create an ArrayList < myNode '> mynodelist and store all myNode values in the
		    public void dfs(int row,int col,TreeNode node){
               
                if(node!=null){
                    myNodeList.add(new myNode(row,col,node.val));
		    	    dfs(row+1,col-1,node.left);
		    	    dfs(row+1,col+1,node.right);
                }
		    	
		    }

			// 1. Create a class myNode and record the row, col and val values
            class myNode{
		        int x,y;
		        int val;
		        public myNode(int x,int y,int val){
			       this.x=x;
			       this.y=y;
			       this.val=val;
		    }
	  }
	  }
	  

Write at the end

If you feel that the writing is good, you might as well share it with others in order to make common progress!

If there are any mistakes in the article, please point them out, and I will listen to them and correct them!

Topics: Algorithm data structure leetcode Interview Binary tree