【多次过】Lintcode 480. 二叉树的所有路径

480. 二叉树的所有路径

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

样例

给出下面这棵二叉树:

   1
 /   \
2     3
 \
  5

所有根到叶子的路径为:

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

解题思路:

    递归。

/**
 * 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> res;
        if(root == NULL)
            return res;
        
        if(root->left == NULL && root->right == NULL) //叶子节点
        {
            res.push_back(to_string(root->val));
            return res;
        }
        
        vector<string> leftS = binaryTreePaths(root->left);
        for(int i=0;i<leftS.size();i++)
            res.push_back(to_string(root->val) + "->" + leftS[i]);
        
        vector<string> rightS = binaryTreePaths(root->right);
        for(int i=0;i<rightS.size();i++)
            res.push_back(to_string(root->val) + "->" + rightS[i]);   
            
        return res;
        
    }
};



猜你喜欢

转载自blog.csdn.net/majichen95/article/details/81060669