Leetcode 257. 二叉树的所有路径

Leetcode 257. 二叉树的所有路径

这个题我做了一早上,原本的思路是通过二叉树的中序遍历完成,但是出错了,不明白问题在哪里,先放着吧,将来回头再看。网上的解法是递归,本质上是中序遍历。

1. 我的解法(中序遍历)

    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {         
            stack<TreeNode *> nodes;
            vector<string> reval;
            
            if(!root)  return reval;
            
            int directionFlag = 0;
            string str = "->";
            
            while(true)
            {           
                travelAlongLeft(root, str, nodes, directionFlag);
                if(nodes.empty())  return reval;
                TreeNode * temp = nodes.top();
                nodes.pop();
                ++directionFlag;
                
                
                if(temp->right == nullptr)
                {
                    str = str.substr(2);
                    reval.push_back(str);
                    str.erase(str.end()-directionFlag);
                }
                else 
                   root = root->right;
                    
            }
            
        }
        void travelAlongLeft(TreeNode* root, string str, stack<TreeNode *> & nodes, int& directionFlag)
        {
            directionFlag = 0 ;
          while(root) 
          { 
              
            str.append(to_string(root->val) + "->"); 
              nodes.push(root);
              root = root->left;
          }
        }
    };

2. 网上的递归解法

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    vector<string> binaryTreePaths(TreeNode* root) {
        // Write your code here
        vector<string>Paths;
        if(root==NULL) return Paths;
        ff(root,Paths,to_string(root->val) );
        return Paths;
    }
    void ff(TreeNode *root,vector<string>&Paths,string strPaths){
        if(root->left==NULL&&root->right==NULL){
            Paths.push_back(strPaths);
            return;
        }
        if(root->left!=NULL)
        ff(root->left,Paths,strPaths+"->"+to_string(root->left->val) );
        if(root->right!=NULL)
        ff(root->right,Paths,strPaths+"->"+to_string(root->right->val) );
 
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值