LeetCode - Medium - 655. Print Binary Tree

Topic

  • Tree

Description

https://leetcode.com/problems/print-binary-tree/

Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:

  • The height of the tree is height and the number of rows m should be equal to height + 1.
  • The number of columns n should be equal to $2^{height+1} - 1$.
  • Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
  • For each node that has been placed in the matrix at position res[r][c], place its left child at $res[r+1][c-2^{height-r-1}]$ and its right child at $res[r+1][c+2^{height-r-1}]$.
  • Continue this process until all the nodes in the tree have been placed.
  • Any empty cells should contain the empty string "".

Return the constructed matrix res.

Example 1:

Input: root = [1,2]
Output: 
[["","1",""],
 ["2","",""]]

Example 2:

Input: root = [1,2,3,null,4]
Output: 
[["","","","1","","",""],
 ["","2","","","","3",""],
 ["","","4","","","",""]]

Constraints:

  • The number of nodes in the tree is in the range $[1, 2^{10}]$.
  • -99 <= Node.val <= 99
  • The depth of the tree will be in the range [1, 10].

Analysis

方法一:BFS,我寫的。

方法二:別人寫的,DFS(或二叉樹的前序遍歷)

Submission

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.lun.util.BinaryTree.TreeNode;

public class PrintBinaryTree {
	
	//方法一:BFS,我寫的
    public List<list<string>&gt; printTree(TreeNode root) {
        
    	int height = getHeight(root);
    	int m = height + 1, n = (int)Math.pow(2, m) - 1;
    	
    	List<string> emptyRow = new ArrayList&lt;&gt;(n);
    	for(int i = 0; i &lt; n; i++)
    		emptyRow.add("");
    	
    	List<list<string>&gt; result = new ArrayList&lt;&gt;();
    	
    	LinkedList<object> queue = new LinkedList&lt;&gt;();
    	queue.offer(root);
    	queue.offer(new int[] {0, (n - 1) / 2});
    	
    	while(!queue.isEmpty()) {
    		
    		List<string> newRow = new ArrayList&lt;&gt;(emptyRow);
    		for(int size = queue.size(); size &gt; 0; size -= 2) {
    			
    			TreeNode node = (TreeNode)queue.poll();
    			int[] index = (int[])queue.poll();
    			int r = index[0], c = index[1];
    			
    			newRow.set(c, String.valueOf(node.val));
    			
    			if(node.left != null) {
    				queue.offer(node.left);
    				queue.offer(new int[] {r + 1, c - (int)Math.pow(2, height - r - 1)});
    			}
    				
    			if(node.right != null) {
    				queue.offer(node.right);
    				queue.offer(new int[] {r + 1, c + (int)Math.pow(2, height - r - 1)});
    			}
    		}
    		result.add(newRow);
    	}
    	
    	return result;
    }
    
    
    public int getHeight(TreeNode root) {
    	if(root == null)
    		return 0;
    	
    	int temp = 0;
    	if(root.left != null || root.right != null)
    		temp = 1;
    	
    	return temp + Math.max(getHeight(root.left), getHeight(root.right));
    }
    
    
    //方法二:別人寫的,DFS(或二叉樹的前序遍歷)
    public List<list<string>&gt; printTree2(TreeNode root) {
        List<list<string>&gt; res = new LinkedList&lt;&gt;();
        int height = root == null ? 1 : getHeight2(root);
        int rows = height, columns = (int) (Math.pow(2, height) - 1);
        List<string> row = new ArrayList&lt;&gt;();
        for(int i = 0; i &lt; columns; i++)  
        	row.add("");
        
        for(int i = 0; i &lt; rows; i++)  
        	res.add(new ArrayList&lt;&gt;(row));
        populateRes(root, res, 0, rows, 0, columns - 1);
        return res;
    }

    public void populateRes(TreeNode root, List<list<string>&gt; res, int nRow, int totalRows, int left, int right) {
        if (nRow == totalRows || root == null) return;
        int mid = left + (right - left) / 2;
        res.get(nRow).set(mid, Integer.toString(root.val));
        populateRes(root.left, res, nRow + 1, totalRows, left, mid - 1);
        populateRes(root.right, res, nRow + 1, totalRows, mid + 1, right);
    }

    public int getHeight2(TreeNode root) {
         if (root == null) return 0;
         return 1 + Math.max(getHeight2(root.left), getHeight2(root.right));
    }
    
}

Test

import static org.junit.Assert.*;
import static org.hamcrest.collection.IsIterableContainingInOrder.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;

public class PrintBinaryTreeTest {

	@Test
	public void testGetHeight() {
		PrintBinaryTree obj = new PrintBinaryTree();

		assertEquals(1, obj.getHeight(BinaryTree.integers2BinaryTree(1, 2)));
		assertEquals(2, obj.getHeight(BinaryTree.integers2BinaryTree(1, 2, 3, null, 4)));
	}
	
	@Test
	@SuppressWarnings({ "rawtypes" })
	public void test() {
		PrintBinaryTree obj = new PrintBinaryTree();
		
		TreeNode root1 = BinaryTree.integers2BinaryTree(1, 2);
		TreeNode root2 = BinaryTree.integers2BinaryTree(1, 2, 3, null, 4);
		
		List[] expected1 = {Arrays.asList("","1",""), //
							Arrays.asList("2","","")};
		
		List[] expected2 = {Arrays.asList("","","","1","","",""), // 
							Arrays.asList("","2","","","","3",""), //
							Arrays.asList("","","4","","","","")};
		
		assertThat(obj.printTree(root1), contains(expected1));
		assertThat(obj.printTree(root2), contains(expected2));
		
		assertThat(obj.printTree2(root1), contains(expected1));
		assertThat(obj.printTree2(root2), contains(expected2));
		
	}
}

</list<string></string></list<string></list<string></string></object></list<string></string></list<string>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章