二叉树的所有路径(binary-tree-paths)
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
代码与思路
package binary_tree_paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* 二叉树的所有路径(binary-tree-paths)
* @param root
* @return
*/
public List<String> binaryTreePaths(TreeNode root) {
dfs(root);
return list;
}
List<String> list = new ArrayList<String>();//叶子节点的路径集合
Stack<Integer> path = new Stack<Integer>();//路径
/**
* 深度遍历
* @param root
*/
private void dfs(TreeNode root){
if(root == null) return;
if(root.left == null && root.right == null){
path.push(root.val);
addPaths(path);
path.pop();
}
path.push(root.val);
if(root.left != null) dfs(root.left);
if(root.right != null) dfs(root.right);
path.pop();
}
/**
* 加到路径中
* @param stack
*/
private void addPaths(Stack<Integer> stack) {
StringBuffer str = new StringBuffer();
for(Integer s:path) {
str.append(s).append("->");
}
String str1 = str.toString();
str1 = str1.substring(0, str1.length()-2);
list.add(str1);
}
}
java代码
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
construct_paths(root, "", paths);
return paths;
}
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);
}
}
}
}