打印二叉树的路径

217 篇文章 1 订阅
174 篇文章 2 订阅
本文介绍了两种方法来打印二叉树的路径:一种是使用递归的方式,从根节点开始,递归遍历左右子树,遇到叶节点时记录路径;另一种是非递归方法,利用两个栈来保存访问路径。提供了相应的代码实现。
摘要由CSDN通过智能技术生成

本题源自leetcode

--------------------------------------------------

思路1 递归:

先访问根节点。然后递归遍历左子树和右子树。遇到叶节点则保存路径。

代码

vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root==NULL)
            return res;
        findPath(root,res,to_string(root->val));
        return res;
    }
    void findPath(TreeNode* root,vector<string>& res,string s){
        if(!root->left && !root->right){
            res.push_back(s);
            return;
        }
        if(root->left){
            findPath(root->left,res,s+"->"+to_string(root->left->val));
        }
        if(root->right){
            findPath(root->right,res,s+"->"+to_string(root->right->val));
        }
    }
   


思路2: 非递归

用俩个栈 来保存访问 路径

代码;

vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        stack<string> str;
        stack<TreeNode*> tree;
        if(root==NULL)
            return res;
        tree.push(root);
        str.push(to_string(root->val));
        while(!tree.empty()){
            TreeNode* p=tree.top();
            tree.pop();
            string s=str.top();
            str.pop();
            if(!p->left && !p->right){
                res.push_back(s);
                continue;
            }
            if(p->left){
                tree.push(p->left);
                str.push(s+"->"+to_string(p->left->val));
            }
            if(p->right){
                tree.push(p->right);
                str.push(s+"->"+to_string(p->right->val));
            }
        }
        return res;
      
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值