LintCode-480: Binary Tree Paths

我用的递归,代码如下:

/**
 * 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) {
        vector<string> result;
        if (!root) return result;
        string path;
        findPath(root, path, result);
        return result;
    }

private:
    void findPath(TreeNode *root, string & path, vector<string> & result) {
        if (root && !root->left && !root->right) { 
            result.push_back(path+to_string(root->val));    
        } else {
            string tempStr=path + to_string(root->val) + "->";
            if (root->left) 
                findPath(root->left, tempStr, result);
            if (root->right)
                findPath(root->right, tempStr, result);
         }
    }
};

注意:

  1. C++里面可以用to_string(int)来把一个int变成string。类似的方法还有springf(), stringstream, etc.

二刷:

class Solution {
public:
    /**
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     *          we will sort your return value in output
     */
    vector<string> binaryTreePaths(TreeNode *root) {
        vector<string> res;
        string str;
        helper(root, res, str);
        return res;
    }
private:
    void helper(TreeNode *root, vector<string> &res, string str) {
        if (!root) return;
        str = str + to_string(root->val);
        if (!root->left && !root->right) {
            res.push_back(str);
            return;
        }
        str = str + "->";
        helper(root->left, res, str);
        helper(root->right, res, str);
        return;
    }
};

还有一个方法是用分治,九章参考答案如下,我感觉写的很好。下次再学习。

public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        if (root == null) {
            return paths;
        }
        
        List<String> leftPaths = binaryTreePaths(root.left);
        List<String> rightPaths = binaryTreePaths(root.right);
        for (String path : leftPaths) {
            paths.add(root.val + "->" + path);
        }
        for (String path : rightPaths) {
            paths.add(root.val + "->" + path);
        }
        
        // root is a leaf
        if (paths.size() == 0) {
            paths.add("" + root.val);
        }
        
        return paths;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值