概述
项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步
1.问题描述
给一棵二叉树,找出从根节点到叶子节点的所有路径。
2.解法
找出所有路径这种问题,一般都是dfs+递归的方法解决即可。
对于二叉树来说,递归的核心在于不断dfs到树的叶子节点,然后再回溯回去。在递归函数中,当遇到叶子节点,即该节点即无左子树又无右子树的时候,就是一条完整的路径。
import java.util.ArrayList;
import java.util.List;
/**
* Created by wanglei on 19/4/14.
*/
public class FindAllPath {
public static TreeNode<Integer> init() {
TreeNode<Integer> root = new TreeNode<>(1);
TreeNode<Integer> node2 = new TreeNode<>(2);
TreeNode<Integer> node3 = new TreeNode<>(3);
TreeNode<Integer> node5 = new TreeNode<>(5);
root.left = node2;
root.right = node3;
node2.right = node5;
return root;
}
public static void helper(TreeNode<Integer> root, String path, List<String> result) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
result.add(path);
return;
}
if (root.left != null) {
helper(root.left, path + "->" + root.left.data.toString(), result);
}
if (root.right != null) {
helper(root.right, path + "->" + root.right.data.toString(), result);
}
}
public static List<String> slove(TreeNode<Integer> root) {
List<String> result = new ArrayList<>();
if (root == null) {
return result;
}
helper(root, root.data.toString(), result);
return result;
}
public static void printArray(List<String> list) {
for(String ele: list) {
System.out.println(ele);
}
}
public static void main(String[] args) {
TreeNode<Integer> root = init();
List<String> result = slove(root);
printArray(result);
}
}
最后
以上就是正直蜡烛为你收集整理的输出树的所有路径的全部内容,希望文章能够帮你解决输出树的所有路径所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复