LeetCode OJ 之 Binary Tree Paths(二叉树路径)

来源:互联网 发布:ae软件破解版 编辑:程序博客网 时间:2024/06/05 16:44

题目:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

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

思路:

前序递归即可。

代码1:

/** * 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> result;        if(root == NULL)            return result;        string path;        binaryTreePaths(root , result , path);        return result;    }    void binaryTreePaths(TreeNode* root , vector<string> &result , string path)     {        if(root == NULL)            return;        if(path.empty())            path += to_string(root->val);        else        {            path += "->";            path += to_string(root->val);        }        if(root->left == NULL && root->right == NULL)        {            result.push_back(path);            return;        }        binaryTreePaths(root->left , result , path);        binaryTreePaths(root->right , result , path);    }};


代码2:

/** * 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> result;        if(root == NULL)            return result;        string path;        binaryTreePaths(root , result , path);        return result;    }    void binaryTreePaths(TreeNode* root , vector<string> &result , string path)     {        if(root == NULL)            return;        if(root->left == NULL && root->right == NULL)        {            result.push_back(path + to_string(root->val));            return;        }        binaryTreePaths(root->left , result , path + to_string(root->val) + "->");        binaryTreePaths(root->right , result , path + to_string(root->val) + "->");    }};


0 0
原创粉丝点击