import java.util.*;
/*树的深度遍历*/
public class Test5 {
public static void main(String[] args) {
TreeNode node1=new TreeNode(1);
TreeNode node2=new TreeNode(2);
TreeNode node3=new TreeNode(3);
TreeNode node4=new TreeNode(4);
TreeNode node5=new TreeNode(5);
node1.left=node2;
node1.right=node3;
node2.left=node4;
node2.right=node5;
//dfsOrder(node1);
List<String> list=show(node1);
System.out.println(list);
}
//这个只是进行树的深度优先遍历,并没有将树的每一条节点进行打印出来
public static void dfsOrder(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode tempNode=stack.pop();
System.out.println(tempNode.val);
if(tempNode.right!=null) {
stack.push(tempNode.right);
}
if(tempNode.left!=null) {
stack.push(tempNode.left);
}
}
}
//输出树的每一条路径
public static void helper(TreeNode 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.val,result);
}
if(root.right!=null) {
helper(root.right,path+"->"+root.right.val,result);
}
}
public static List<String> show(TreeNode root){
List<String> list=new ArrayList<>();
helper(root,root.val.toString(),list);
return list;
}
}
树的路径遍历
最新推荐文章于 2021-10-21 20:24:14 发布
该博客主要介绍了如何使用Java实现树的深度优先遍历(DFS),并展示了一种方法来打印出树的所有路径。通过创建一个Stack来辅助DFS遍历,从根节点开始,将节点压入栈中,然后依次弹出节点并访问其左右子节点,直到所有节点都被遍历。此外,还提供了一个辅助方法用于收集树的所有路径,将路径字符串添加到结果列表中。
1440

被折叠的 条评论
为什么被折叠?



