二叉树层序遍历形式输出
| 105 | |
| 106 | // 二叉树层序遍历形式输出 |
| 107 | string treeNodeToString(TreeNode* root) { |
| 108 | if (root == nullptr) { |
| 109 | return "[]"; |
| 110 | } |
| 111 | |
| 112 | string output = ""; |
| 113 | queue<TreeNode*> q; |
| 114 | q.push(root); |
| 115 | while(!q.empty()) { |
| 116 | TreeNode* node = q.front(); |
| 117 | q.pop(); |
| 118 | |
| 119 | if (node == nullptr) { |
| 120 | output += "null, "; |
| 121 | continue; |
| 122 | } |
| 123 | |
| 124 | output += to_string(node->val) + ", "; |
| 125 | q.push(node->left); |
| 126 | q.push(node->right); |
| 127 | } |
| 128 | return "[" + output.substr(0, output.length() - 2) + "]"; |
| 129 | } |
| 130 | |
| 131 | |
| 132 |