二叉树的所有路径

来源:互联网 发布:杀戮游戏网络电影 编辑:程序博客网 时间:2024/06/06 05:45

题目:

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

样例

给出下面这棵二叉树:

   1 /   \2     3 \  5

所有根到叶子的路径为:

[  "1->2->5",  "1->3"]

思路:

这个题使用了引用,方便了很多,这道题也又写了一个函数,all(root,ss,to_string(root->val)); 在函数里使用了递归。

代码:

/**
 * 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> ss; 
        if(root==NULL) return ss; 
        all(root,ss,to_string(root->val)); 
        return ss; 
    } 
    void all(TreeNode *root,vector<string>&str,string strPaths){ 
        if(root->left==NULL&&root->right==NULL){ 
            str.push_back(strPaths); 
            return; 
        } 
        if(root->left!=NULL) 
        all(root->left,str,strPaths+"->"+to_string(root->left->val)); 
        if(root->right!=NULL) 
        all(root->right,str,strPaths+"->"+to_string(root->right->val)); 
    } 
        /*int top=-1;
        //stack<int>st;
        vector<string>aa;
        vector<int>ss;
        TreeNode *s[100];
        string h,k;
       while(root!=NULL||top!=-1)
       {
           while(root!=NULL)
           {
               //cout<<root->val;
               ss.push_back(root->val);
               //st.push(root->val)
               s[++top]=root;
               root=root->left;
           }
           h=to_string(s[0]->val);
           for(int i=1;i<=top+1;i++)
           { h=h+"->"+to_string(s[i]->val);
           }
           aa.push_back(h);
           h=k;
           if(top!=-1)
           { root=s[top--];
             root=root->right;
           }
       }
       return aa;
    }*/
};

感想:

我一开始利用了前序遍历非递归算法,写了一个程序,就是下面那个,老是不对,也改不对,就又换了个,确实这个方便了许多。

0 0
原创粉丝点击