leetcode 257 Binary Tree Paths

python:

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        path = ''
        res = []
        self.TreePaths(root, path, res)
        return res
    
    def TreePaths(self, root, path, result):
        if not root:
            return result
        path += '->' + str(root.val)
        if not root.left and not root.right:
            result.append(path[2:])
            return result
        else:
            if root.left:
                self.TreePaths(root.left, path, result)
            if root.right:
                self.TreePaths(root.right, path, result)

c++:

class Solution {
private:
    string path = "";
    vector<string> res;
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root)
            return res;
        TreePaths(root, path+to_string(root->val));         
        return res;
    }
    
    void TreePaths(TreeNode* root, string path){
        if(!root->left && !root->right){
            res.push_back(path);
            return;
        }
        if(root->left)
            TreePaths(root->left, path+"->"+to_string(root->left->val));
        if(root->right)
            TreePaths(root->right, path+"->"+to_string(root->right->val));
    }
};

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82964191