OJ lintcode 二叉树的所有路径

给一棵二叉树,找出从根节点到叶子节点的所有路径。

《OJ lintcode 二叉树的所有路径》 image.png

/**
 * 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
     */
    //void path(TreeNode* p,string str,vector<string> & vs){
    //  if(p==NULL){
    //      //遍历到结尾
    //      vs.push_back(str);
    //      return;
    //  }
    //  /*  if((p->left==NULL)&&(p->right=NULL)){
    //          return ;
    //      }*/
    //  else{
    //      stringstream ss;
    //      ss<<p->val;
    //      string cur_str;
    //      ss>>cur_str;
    //      str=str+"->"+cur_str;
    //      
    //      //if(p->left!=NULL){
    //          path(p->left,str,vs);
    //  //  }
    //  //  if(p->right!=NULL){
    //          path(p->right,str,vs);
    //  //  }
    //  }
    //}
    string int_to_string(int val){
        stringstream int_to_s;
        string ret_str;
        int_to_s <<val;
        int_to_s>>ret_str;
        return ret_str;
    }
    void path2(TreeNode* p,string str,vector<string> & vs){


        if((p->left==NULL)&&(p->right==NULL)){
            string cur_str=str+"->"+int_to_string(p->val);
            vs.push_back(cur_str);
        }
        else{
            string cur_str=int_to_string(p->val);
            cur_str=str+"->"+cur_str;
            if((p->left!=NULL)&&(p->right==NULL)){
                path2(p->left,cur_str,vs);
            }
            if((p->left==NULL)&&(p->right!=NULL)){
                path2(p->right,cur_str,vs);
            }
            if((p->left!=NULL)&&(p->right!=NULL)){
                path2(p->left,cur_str,vs);
                path2(p->right,cur_str,vs);
            }
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> vs;
        // Write your code here
        if(root!=NULL){
            int val=root->val;
            stringstream ss;
            ss<<val;
            string str;
            ss>>str;
            /*if(root->left!=NULL){
                path(root->left,str,vs);
            }
            if(root->right!=NULL){
                path(root->right,str,vs);
            }*/
            
                
            if((root->left==NULL)&&(root->right==NULL)){
                vs.push_back(str);
                return vs;
            }
            if(root->left!=NULL){
                path2(root->left,str,vs);
            }
            if(root->right!=NULL){
                path2(root->right,str,vs);
            }
        }

        return vs;
    }
};
    原文作者:zhaozhengcoder
    原文地址: https://www.jianshu.com/p/9ef3e0cd8fce
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞