LeetCode.655 Print Binary Tree(对左右子树位置确定)

本文介绍了一种新的二叉树打印方式,该方法能够将二叉树的结构以二维字符串数组的形式展示出来,便于直观地理解二叉树的结构特征。通过递归算法和精确的坐标计算,实现了树的高度、宽度与打印格式之间的对应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:

Input:
     1
    /
   2
Output:
[["", "1", ""],
 ["2", "", ""]]

Example 2:

Input:
     1
    / \
   2   3
    \
     4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

Example 3:

Input:
      1
     / \
    2   5
   / 
  3 
 / 
4 
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

Note:The height of binary tree is in the range of [1, 10].

分析:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<String>> printTree(TreeNode root) {
        //给定二叉树,返回按期规定形式返回,即每层位置均保留上下层结构
        //思路:先求出树的高度,即每层最大个数为2^h-1,然后根据每层所属的层数,将节点位置放置
        //关键点:每个节点的坐标折中取值结果,左孩子的j=(i+j)/2-1;右孩子i=(i+j)/2+1
        List<List<String>> list=new ArrayList<>();
        if(root==null) return list;
        
        int height=root==null?1:getHeight(root);
        int row=height,col=(int)(Math.pow(2,height)-1);
        List<String> subList=new ArrayList<>();
        for(int i=0;i<col;i++){
            //填充一行“”
            subList.add("");
        }
        for(int j=0;j<row;j++){
            //填充整个数据
            list.add(new ArrayList<>(subList));
        }
        //递归实现
        backtrace(root,list,0,row,0,col-1);
        
        return list;
    }
    
    //递归将数据放入数组中,当判断到叶子节点是即停止
    public void backtrace(TreeNode root,List<List<String>> list,int row,int totalRows,int i,int j){
        if(root==null||row==totalRows) return ;
        //在某个位置更改值用set,因为add会增加空间
        list.get(row).set((i+j)/2,String.valueOf(root.val));
        backtrace(root.left,list,row+1,totalRows,i,(i+j)/2-1);
        backtrace(root.right,list,row+1,totalRows,(i+j)/2+1,j);
    }
    
    //求树高度
    public int getHeight(TreeNode root){
        if(root==null) return 0;
        int left=getHeight(root.left);
        int right=getHeight(root.right);
        return Math.max(left,right)+1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值