_莫相逢

导航

LeetCode 257 二叉树的所有路径

题目:

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 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> ans;
        if(root == NULL)
            return ans;
        if(!root->left && !root->right)
            ans.push_back(to_string(root->val));
        vector<string> leftSub = binaryTreePaths(root->left);
        for(int i=0; i<leftSub.size(); ++i)
            ans.push_back(to_string(root->val) + "->" + leftSub[i]);
        vector<string> rightSub = binaryTreePaths(root->right);
        for(int i=0; i<rightSub.size(); ++i)
            ans.push_back(to_string(root->val) + "->" + rightSub[i]);
      return ans;      
    }
};

参考来源https://blog.csdn.net/my_clear_mind/article/details/82283939

 

法二:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void DFS(TreeNode* root, string temp, vector<string> &ans)
13     {
14         if(root == NULL) {
15             return ;
16         }
17         if(root->left == NULL && root->right == NULL) {
18             temp += to_string(root->val);
19             ans.push_back(temp);
20             return ;
21         }
22         if(root->left) {
23             DFS(root->left, temp + to_string(root->val) + "->", ans);
24         }
25         if(root->right) {
26             DFS(root->right, temp + to_string(root->val) + "->", ans);
27         }
28     }
29     vector<string> binaryTreePaths(TreeNode* root) {
30         vector<string> ans;
31         if(root == NULL)
32             return ans;
33         DFS(root, "", ans);
34         return ans;
35     }
36 };

 

posted on 2019-04-07 21:47  莫晓风  阅读(123)  评论(0编辑  收藏  举报