二叉树路径-lintcode

这道题的做法就是把模式记下来。源函数是传入一个二叉树(treeNode*),但是我们应该自己再实现一个函数search用于传递结点、vector<string>的引用和string path,这样可以递归的去调用search,当然,在search中一开始就有结束条件,遇到结束条件会return。随着不断地递归,只要不满足结束条件--------root的left和right都为NULL,该递归就会不断地增长path,并在结束时将这条path push_back()进vector中。

下面是C++代码:

/**
 * 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> vecStr;
        if (root == NULL){
            return vecStr;
        }
        stringstream ss;
        ss<<root->val;
        string temp = ss.str();
        search(root,temp,vecStr);
        return vecStr;
    }
    void search(TreeNode* root, string path, vector<string>& vecStr){
        //if (root == NULL){
          //  return;
        //}
        if (root->right == NULL && root->left == NULL){
            vecStr.push_back(path);
            return;
        }
        string path1 = path;
        if (root->left != NULL) {
            stringstream ss;
            ss<<root->left->val;
            string temp = ss.str();
            //string temp(root->left->val);
            path = path + "->" + temp;
            search(root->left, path,vecStr);
        }
        if (root->right != NULL) {
            stringstream ss;
            ss<<root->right->val;
            string temp = ss.str();
            path = path1 + "->" + temp;
            search(root->right, path, vecStr);
        }
    }
}; //43ms


python代码:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    # @param {TreeNode} root the root of the binary tree
    # @return {List[str]} all root-to-leaf paths
    def binaryTreePaths(self, root):
        # Write your code here
        li = []
        if root == None:
            return li
        path = str(root.val)
        self.search(root,path,li)
        return li
    def search(self, root, path, li):
        if root.left==None and root.right==None:
            li.append(path)
            return
        pathtemp = path
        if root.left != None:
            path += '->' + str(root.left.val)
            self.search(root.left, path, li)
        if root.right != None:
            path = pathtemp + '->' + str(root.right.val)
            self.search(root.right, path, li)	//460ms



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值