LeetCode 257. Binary Tree Paths(二叉树的所有路径)
题目描述
英文
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
中文
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解法一
思路
这题可以用递归的方法来做,从根结点开始,对其左右子结点进行递归,递归的终止条件就是碰到叶子结点。每一层递归的输入是什么呢?结合题意,就是上层递归的输入加上上层结点的值了;而对于根结点,其输入就是空字符串。
以示例为例:
- 第一次递归:输入
''
,输出'1'
。 - 第二次递归:输入
'1'
,左子结点输出'1->2'
,右子结点输出'1->3'
(右子结点为叶子结点,停止递归)。 - 第三次递归:输入
'1->2'
,左子结点的右子结点输出'1->2->5'
(左子结点的右子结点为叶子结点,停止递归)。 - 输出:
'1->3'
和'1->2->5'
。
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def paths(root, path, result):
if root.left is None and root.right is None:
result.append(path + str(root.val))
if root.left is not None:
paths(root.left, path + str(root.val) + '->', result)
if root.right is not None:
paths(root.right, path + str(root.val) + '->', result)
result = []
if root is not None:
paths(root, '', result)
return result
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
class Utils {
public void paths(TreeNode root, String path, List<String> result) {
if (root.left == null && root.right == null) {
result.add(path + root.val);
}
if (root.left != null) {
paths(root.left, path + root.val + "->", result);
}
if (root.right != null) {
paths(root.right, path + root.val + "->", result);
}
}
}
Utils utils = new Utils();
List<String> result = new ArrayList<>();
if (root != null) {
utils.paths(root, "", result);
}
return result;
}
}
C++
/**
* 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) {
class Utils {
public:
void paths(TreeNode *root, string path, vector<string> &result) {
if (root->left == nullptr && root->right == nullptr) {
result.push_back(path + to_string(root->val));
}
if (root->left != nullptr) {
paths(root->left, path + to_string(root->val) + "->", result);
}
if (root->right != nullptr) {
paths(root->right, path + to_string(root->val) + "->", result);
}
}
};
vector<string> result;
if (root != nullptr) {
Utils utils;
utils.paths(root, "", result);
}
return result;
}
};