logologo

打印二叉树

Sep 11, 2023

class Solution {
 private:
  void printInOrder(Node *head, int height, string to, int len) {
    if (head == nullptr) return;
    printInOrder(head->right, height + 1, "v", len);
    string val = to + to_string(head->value) + to;
    int lenM = val.length(), lenL = (len - lenM) / 2, lenR = len - lenM - lenL;

    val = getSpace(lenL) + val + getSpace(lenR);
    cout << (getSpace(height * len) + val) << endl;
    printInOrder(head->left, height + 1, "^", len);
  }
  string getSpace(int num) {
    string space = " ";
    for (int i = 0; i < num; i++) space.append(space);
    return space;
  }

 public:
  void printTree(Node *head) {
    cout << "Binary Tree:" << endl;
    printInOrder(head, 0, "H", 2);
    cout << endl;
  }
};

C++Java
浙ICP备2021022773号    2022-PRESENT © ZhengKe