LeetCode*257. Binary Tree Paths

LeetCode题目链接

题目:

Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:

All root-to-leaf paths are:

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

答案一:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res, left, right;
        if (root == NULL) {
            return res;
        }
        if (root->left == NULL && root->right == NULL) {
            //print the answer
            res.push_back(to_string(root->val));
        } else {
            if (root->left) {
                left = binaryTreePaths(root->left);
                for (int i = 0; i < left.size(); i++) {
                    left[i] = to_string(root->val) + "->" + left[i];
                    res.push_back(left[i]);
                }
            }
            if (root->right) {
                right = binaryTreePaths(root->right);
                for (int i = 0; i < right.size(); i++) {
                    right[i] = to_string(root->val) + "->" + right[i];
                    res.push_back(right[i]);
                }
            }
        }
        return res;
    }
};

答案二:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        
        if (root == NULL) {
            return res;
        }
        binaryTreePaths(res, root, to_string(root->val)); 
        
        return res;
    }
    
    void binaryTreePaths(vector<string>& res, TreeNode* node, string s) {
        if (node->left == NULL && node->right == NULL) {
            res.push_back(s);
            return;
        } else {
            if (node->left) {
                binaryTreePaths(res, node->left, s + "->" + to_string(node->left->val));
            }
            if (node->right) {
                binaryTreePaths(res, node->right, s + "->" + to_string(node->right->val));
            }
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容