二叉树的所有路径

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;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值