首页 > 代码库 > Leetcode 257. Binary Tree Paths

Leetcode 257. Binary Tree Paths

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"]
分析:典型的深度优先搜索,dfs函数思路为:
dfs函数中参数传入一个string,该String将每次结点的值连接起来,直到递归出口的时候返回;
当该结点有左孩子的时候,将左孩子的值连接到字符串尾部;
当该结点有右孩子的时候,将右孩子的值连接到字符串尾部;
当该结点无左右孩子的时候,将字符串push入数组后return;
 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(vector<string> &v, TreeNode* root, string s){13         if(root -> left == NULL && root -> right == NULL){14             v.push_back(s);15             return;16         }17         if(root -> left != NULL)18             dfs(v, root -> left, s + "->" + to_string(root -> left -> val));19         if(root -> right != NULL)20             dfs(v, root -> right, s + "->" + to_string(root -> right -> val));21     }22     vector<string> binaryTreePaths(TreeNode* root) {23         vector<string> v;24         if(root == NULL)25             return v;26         dfs(v, root, to_string(root -> val));27         return v;28     }29 };

 

 

Leetcode 257. Binary Tree Paths