给定一个二叉树,返回所有根节点到叶子节点的路径。
Input:
1
/
2 3
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
难点:返回的是vector<string>的容器类型,需要对容器遍历读写操作。
思路:运用3个容器,分别为接收左子树路径的 res_left,接收右子树路径的 res_right,和总的路径的 res. 对每次遍历所得到的 res_left 和 res_right 遍历,将里面的已有路径读出来,加上当前节点的值,再写入到总的路径容器 res 中,最后返回 res.
vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; vector<string> res_left; vector<string> res_right; vector<string> res; if (root->left != NULL) res_left = binaryTreePaths(root->left); if (root->right != NULL) res_right = binaryTreePaths(root->right); if (res_left.size() == 0 && res_right.size() == 0) { return{ to_string(root->val) }; } for (int i = 0; i < res_left.size(); i++) { res.push_back(to_string(root->val) + "->" + res_left[i]); } for (int i = 0; i < res_right.size(); i++) { res.push_back(to_string(root->val) + "->" + res_right[i]); } return res; }
Java版:
刷第二遍,感觉利用递归 + 深搜,将每一次遍历的路线都记录下来,当节点是叶子节点时,将记录下来的路径加到结果集中。
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> ans = new ArrayList<>(); binaryTreePathsDFS(root, "", ans); return ans; } public void binaryTreePathsDFS(TreeNode root, String path, List<String> ans){ if(root == null) return; path += root.val; if(root.left == null && root.right == null) ans.add(path); else{ binaryTreePathsDFS(root.left, path+"->",ans); binaryTreePathsDFS(root.right, path+"->",ans); } } }