博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 655. Print Binary Tree 打印二叉树
阅读量:5245 次
发布时间:2019-06-14

本文共 8102 字,大约阅读时间需要 27 分钟。

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    /   2Output:[["", "1", ""], ["2", "", ""]]

Example 2:

Input:     1    / \   2   3    \     4Output:[["", "", "", "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].

给一个二叉树,按照以下规则以m * n二维数组的形式打印出来:

1. 行号m应该等于给定二叉树的高度。

2. 列号n应始终为奇数。
3. 根节点的值(以字符串格式)应该放在它可以放入的第一行的正中间。 根节点所属的列和行将剩余空间分成两部分(左下部分和右下部分)。 您应该在左下部分打印左子树,并在右下部分打印右子树。 左下部和右下部应具有相同的尺寸。 即使一个子树不是,而另一个子树不是,你也不需要为无子树打印任何东西,但仍然需要留出与其他子树一样大的空间。 但是,如果两个子树都没有,那么您不需要为它们留出空间。
4. 每个未使用的空间应包含一个空字符串""。
5. 按照相同的规则打印子树。

解法:递归(Recursion),首先求出二叉树的深度来确定列,二维数组的列是2 ** height -1,height是二叉树深度。然后递归处理每一层,每一行中根节点的位置是:pos-2**(height - h - 1),pos是上一层的根节点的位置。

Java:

public List
> printTree(TreeNode root) { List
> res = new LinkedList<>(); int height = root == null ? 1 : getHeight(root); int rows = height, columns = (int) (Math.pow(2, height) - 1); List
row = new ArrayList<>(); for(int i = 0; i < columns; i++) row.add(""); for(int i = 0; i < rows; i++) res.add(new ArrayList<>(row)); populateRes(root, res, 0, rows, 0, columns - 1); return res;}public void populateRes(TreeNode root, List
> res, int row, int totalRows, int i, int j) { if (row == totalRows || root == null) return; res.get(row).set((i+j)/2, Integer.toString(root.val)); populateRes(root.left, res, row+1, totalRows, i, (i+j)/2 - 1); populateRes(root.right, res, row+1, totalRows, (i+j)/2+1, j);}public int getHeight(TreeNode root) { if (root == null) return 0; return 1 + Math.max(getHeight(root.left), getHeight(root.right));}

Python:

class Solution(object):    def printTree(self, root):        """        :type root: TreeNode        :rtype: List[List[str]]        """        def get_height(node):            return 0 if not node else 1 + max(get_height(node.left), get_height(node.right))                def update_output(node, row, left, right):            if not node:                return            mid = (left + right) / 2            self.output[row][mid] = str(node.val)            update_output(node.left, row + 1 , left, mid - 1)            update_output(node.right, row + 1 , mid + 1, right)                    height = get_height(root)        width = 2 ** height - 1        self.output = [[''] * width for i in xrange(height)]        update_output(node=root, row=0, left=0, right=width - 1)        return self.output

Python:  

class Solution(object):    def printTree(self, root):        """        :type root: TreeNode        :rtype: List[List[str]]        """        def get_height(node):            if not node:                return 0            return 1 + max(get_height(node.left), get_height(node.right))        rows = get_height(root)        cols = 2 ** rows - 1        res = [['' for _ in range(cols)] for _ in range(rows)]        def traverse(node, level, pos):            if not node:                return            left_padding, spacing = 2 ** (rows - level - 1) - 1, 2 ** (rows - level) - 1            index = left_padding + pos * (spacing + 1)            print(level, index, node.val)            res[level][index] = str(node.val)            traverse(node.left, level + 1, pos << 1)            traverse(node.right, level + 1, (pos << 1) + 1)        traverse(root, 0, 0)        return res  

Python:

class Solution(object):    def printTree(self, root):        """        :type root: TreeNode        :rtype: List[List[str]]        """        import math        def dfs(root, h):            if root:                return max(dfs(root.left,h+1), dfs(root.right,h+1))            else :                return h        height = dfs(root, 0)        width = 2 ** height -1        # 初始化        res = [ ["" for j in range(width)] for i in range(height)]        # dfs print        def dfs_print(res,root,h,pos):            if root:                res[h - 1][pos] = '%d' % root.val                dfs_print(res, root.left, h+1, pos-2**(height - h - 1))                dfs_print(res, root.right, h+1, pos+2**(height - h - 1))        dfs_print(res,root,1,width/2)        return res

Python:

# Time:  O(h * 2^h)# Space: O(h * 2^h)class Solution(object):    def printTree(self, root):        """        :type root: TreeNode        :rtype: List[List[str]]        """        def getWidth(root):            if not root:                return 0            return 2 * max(getWidth(root.left), getWidth(root.right)) + 1        def getHeight(root):            if not root:                return 0            return max(getHeight(root.left), getHeight(root.right)) + 1        def preorderTraversal(root, level, left, right, result):            if not root:                return            mid = left + (right-left)/2            result[level][mid] = str(root.val)            preorderTraversal(root.left, level+1, left, mid-1, result)            preorderTraversal(root.right, level+1, mid+1, right, result)        h, w = getHeight(root), getWidth(root)        result = [[""] * w for _ in xrange(h)]        preorderTraversal(root, 0, 0, w-1, result)        return result

C++:  

class Solution {public:    vector
> printTree(TreeNode* root) { int h = getHeight(root), w = pow(2, h) - 1; vector
> res(h, vector
(w, "")); helper(root, 0, w - 1, 0, h, res); return res; } void helper(TreeNode* node, int i, int j, int curH, int height, vector
>& res) { if (!node || curH == height) return; res[curH][(i + j) / 2] = to_string(node->val); helper(node->left, i, (i + j) / 2, curH + 1, height, res); helper(node->right, (i + j) / 2 + 1, j, curH + 1, height, res); } int getHeight(TreeNode* node) { if (!node) return 0; return 1 + max(getHeight(node->left), getHeight(node->right)); }};

C++:

class Solution {public:    vector
> printTree(TreeNode* root) { int h = getHeight(root), w = pow(2, h) - 1, curH = -1; vector
> res(h, vector
(w, "")); queue
q{ {root}}; queue
> idxQ{ { {0, w - 1}}}; while (!q.empty()) { int n = q.size(); ++curH; for (int i = 0; i < n; ++i) { auto t = q.front(); q.pop(); auto idx = idxQ.front(); idxQ.pop(); if (!t) continue; int left = idx.first, right = idx.second; int mid = left + (right - left) / 2; res[curH][mid] = to_string(t->val); q.push(t->left); q.push(t->right); idxQ.push({left, mid}); idxQ.push({mid + 1, right}); } } return res; } int getHeight(TreeNode* node) { if (!node) return 0; return 1 + max(getHeight(node->left), getHeight(node->right)); }};

  

  

  

 

转载于:https://www.cnblogs.com/lightwindy/p/9859912.html

你可能感兴趣的文章
Html 小插件5 百度搜索代码2
查看>>
P1107 最大整数
查看>>
多进程与多线程的区别
查看>>
Ubuntu(虚拟机)下安装Qt5.5.1
查看>>
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
查看>>
java 常用命令
查看>>
CodeForces Round #545 Div.2
查看>>
卷积中的参数
查看>>
51nod1076 (边双连通)
查看>>
Item 9: Avoid Conversion Operators in Your APIs(Effective C#)
查看>>
学习Spring Boot:(二十八)Spring Security 权限认证
查看>>
深入浅出JavaScript(2)—ECMAScript
查看>>
STEP2——《数据分析:企业的贤内助》重点摘要笔记(六)——数据描述
查看>>
ViewPager的onPageChangeListener里面的一些方法参数:
查看>>
Jenkins关闭、重启,Jenkins服务的启动、停止方法。
查看>>
CF E2 - Array and Segments (Hard version) (线段树)
查看>>
Linux SPI总线和设备驱动架构之四:SPI数据传输的队列化
查看>>
SIGPIPE并产生一个信号处理
查看>>
CentOS
查看>>
Linux pipe函数
查看>>