二叉樹的所有路徑
給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑爲: 1->2->5, 1->3
/* Definition for a binary tree node. */
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
方法一:遞歸
最直觀的方法是使用遞歸。在遞歸遍歷二叉樹時,需要考慮當前的節點和它的孩子節點。如果當前的節點不是葉子節點,則在當前的路徑末尾添加該節點,並遞歸遍歷該節點的每一個孩子節點。如果當前的節點是葉子節點,則在當前的路徑末尾添加該節點後,就得到了一條從根節點到葉子節點的路徑,可以把該路徑加入到答案中。
class Solution {
public void construct_paths(TreeNode root, String path, LinkedList<String> paths) {
if (root != null) {
path += Integer.toString(root.val);
if ((root.left == null) && (root.right == null)) // 當前節點是葉子節點
paths.add(path); // 把路徑加入到答案中
else {
path += "->"; // 當前節點不是葉子節點,繼續遞歸遍歷
construct_paths(root.left, path, paths);
construct_paths(root.right, path, paths);
}
}
}
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
construct_paths(root, "", paths);
return paths;
}
}
方法二:迭代
上面的算法也可以使用迭代(寬度優先搜索)的方法實現。我們維護一個隊列,存儲節點以及根到該節點的路徑。一開始這個隊列裏只有根節點。在每一步迭代中,我們取出隊列中的首節點,如果它是一個葉子節點,則將它對應的路徑加入到答案中。如果它不是一個葉子節點,則將它的所有孩子節點加入到隊列的末尾。當隊列爲空時,迭代結束。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
if (root == null)
return paths;
LinkedList<TreeNode> node_stack = new LinkedList();
LinkedList<String> path_stack = new LinkedList();
node_stack.add(root);
path_stack.add(Integer.toString(root.val));
TreeNode node;
String path;
while (!node_stack.isEmpty()) {
node = node_stack.pollLast();
path = path_stack.pollLast();
if ((node.left == null) && (node.right == null))
paths.add(path);
if (node.left != null) {
node_stack.add(node.left);
path_stack.add(path + "->" + Integer.toString(node.left.val));
}
if (node.right != null) {
node_stack.add(node.right);
path_stack.add(path + "->" + Integer.toString(node.right.val));
}
}
return paths;
}
}