655. Print Binary Tree

本文介绍了一种算法,用于将二叉树以二维字符串数组的形式打印出来。遵循特定规则,确保根节点位于第一行中央,并按相同规则递归打印左右子树。

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].

 

class Solution {
public:
    vector<vector<string>> printTree(TreeNode* root) {
        int h = get_height(root), w = get_width(root);
        vector<vector<string>> ans(h, vector<string>(w, ""));
        helper(ans, root, 0, 0, w-1);
        return ans;
    }
private:
    int get_height(TreeNode* p) {
        if (!p) return 0;
        int left = get_height(p->left), right = get_height(p->right);
        return max(left, right)+1;
    }
    // width is the max(left, right)*2+1
    int get_width(TreeNode* p) {
        if (!p) return 0;
        int left = get_width(p->left), right = get_width(p->right);
        return max(left, right)*2+1;
    }
    // always put the value in the middle of the range.
    void helper(vector<vector<string>>& ans, TreeNode* p, int level, int l, int r) {
        if (!p) return;
        int mid = l+(r-l)/2;
        ans[level][mid] = to_string(p->val);
        helper(ans, p->left, level+1, l, mid-1);
        helper(ans, p->right, level+1, mid+1, r);
    }
};

 

 

 

 

### `void preorder(binarytree tree)` 函数实现思路 前序遍历(Preorder Traversal)是一种二叉树的遍历方式,其遍历顺序为:根节点 -> 左子树 -> 右子树。`void preorder(binarytree tree)` 函数的目的就是实现对二叉树的前序遍历。 ### 递归实现 以下是使用递归方式实现 `void preorder(binarytree tree)` 函数的示例代码: ```python class BinaryTree: def __init__(self, root_val): self.key = root_val self.leftChild = None self.rightChild = None def preorder(self): print(self.key) if self.leftChild: self.leftChild.preorder() if self.rightChild: self.rightChild.preorder() # 使用示例 if __name__ == "__main__": # 创建一个简单的二叉树 root = BinaryTree(1) root.leftChild = BinaryTree(2) root.rightChild = BinaryTree(3) root.leftChild.leftChild = BinaryTree(4) root.leftChild.rightChild = BinaryTree(5) # 调用前序遍历函数 root.preorder() ``` 上述代码定义了一个 `BinaryTree` 类,其中的 `preorder` 方法实现了前序遍历。在 `preorder` 方法中,首先打印当前节点的值,然后递归地调用 `preorder` 方法遍历左子树和右子树。 ### 非递归实现 也可以使用栈来实现非递归的前序遍历,以下是示例代码: ```python class BinaryTree: def __init__(self, val): self.val = val self.left = None self.right = None def preorder(root): if not root: return stack = [root] while stack: node = stack.pop() print(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) # 使用示例 if __name__ == "__main__": # 创建一个简单的二叉树 root = BinaryTree(1) root.left = BinaryTree(2) root.right = BinaryTree(3) root.left.left = BinaryTree(4) root.left.right = BinaryTree(5) # 调用前序遍历函数 preorder(root) ``` 在非递归实现中,使用一个栈来模拟递归调用的过程。首先将根节点压入栈中,然后循环取出栈顶节点进行访问,并将其右子节点和左子节点依次压入栈中。 ### 使用方法 - **创建二叉树**:首先需要创建一个二叉树的实例,可以根据实际需求构建不同结构的二叉树。 - **调用 `preorder` 函数**:将创建好的二叉树的根节点作为参数传递给 `preorder` 函数,即可完成前序遍历并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值