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;
}
}
树的路径遍历
最新推荐文章于 2022-03-16 18:41:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)