lintcode程序员

480. 二叉树的所有路径

2018-01-24  本文已影响21人  和蔼的zhxing

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

给出下面这棵二叉树:

   1
 /   \
2     3
 \
  5

所有根到叶子的路径为:

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

递归

讲真我见到递归真的是害怕,也没办法讲,这也是参考的别人的答案,过两天再让我写我可能就写不出来了,这个看了看理解了一点点,就先放在这里吧,也许写的多了就懂了也不一定:

 vector<string> binaryTreePaths(TreeNode* root) 
     {
         vector<string> res;
         if(!root)
            return res;
         binaryTreePathsCore(root,res,to_string(root->val));
            return res;
         
     }
     
     
     
    void binaryTreePathsCore(TreeNode *root,vector<string> &vstring,string str)
     {
         if(root->left==NULL&&root->right==NULL)
         {
             vstring.push_back(str);
             return;
         }
         if(root->left)
         {
             binaryTreePathsCore(root->left,vstring,str+"->"+to_string(root->left->val));
         }
          if(root->right)
         {
             binaryTreePathsCore(root->right,vstring,str+"->"+to_string(root->right->val));
         }
         
     }
     
上一篇 下一篇

猜你喜欢

热点阅读