刷题day36:二叉树的所有路径

题意描述:

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

 需要利用回溯,要把每一条路径记录下来。回溯过程如图所示:

需要注意,写代码的事需要将回溯和递归写在同一个花括号。

递归法C++代码如下:

class Solution {
private:
    void travelsal(TreeNode* cur, vector<int>& path, vector<string>& result){
        path.push_back(cur->val);
        if(cur->left == NULL && cur->right == NULL){
            string sPath;
            for (int i = 0; i < path.size() - 1; i++) {  // 将path里记录的路径转为string格式
                sPath += to_string(path[i]);
                sPath += "->";
            }
            sPath += to_string(path[path.size() - 1]);
            result.push_back(sPath);
            return ;
        }
        if(cur->left){
            travelsal(cur->left, path, result);
            path.pop_back();  //回溯
        }
        if(cur->right){
            travelsal(cur->right, path, result);
            path.pop_back();
        }
    }
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        vector<int> path;
        if(root == NULL){
            return result;
        }
        travelsal(root, path, result);
        return result;
    }
};

迭代法C++代码如下:

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        stack<TreeNode*> treeSt;// 保存树的遍历节点
        stack<string> pathSt;   // 保存遍历路径的节点
        vector<string> result;  // 保存最终路径集合
        if(root == NULL){
            return result;
        }
        treeSt.push(root);
        pathSt.push(to_string(root->val));
        while(!treeSt.empty()){
            TreeNode* cur = treeSt.top();
            treeSt.pop();
            string path = pathSt.top();
            pathSt.pop();
            if(cur->left == NULL && cur->right == NULL){
                result.push_back(path);
            }
            if(cur->right){
                treeSt.push(cur->right);
                pathSt.push(path + "->" + to_string(cur->right->val));
            }
            if(cur->left){
                treeSt.push(cur->left);
                pathSt.push(path + "->" + to_string(cur->left->val));
            }
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值