关于树的遍历

创建案例

public static void main(String[] args) {
    // 根节点为 1
    // 左子节点为 2,右子节点为 3     2 的左子节点为 4,右子节点为 5
    // 3 的左子节点为 6,右子节点为 7    4 的左子节点为 8,右子节点为 9     5 的左子节点为 10
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(2, new TreeNode(4, new TreeNode(8), new TreeNode(9)), new TreeNode(5, new TreeNode(10), null));
    root.right = new TreeNode(3, new TreeNode(6), new TreeNode(7));
    pre(root);
    System.out.println();
    mid(root);
    System.out.println();
    after(root);
    System.out.println();
    tier(root);
}
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) {this.val = val;}
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

层序遍历

public static void tier(TreeNode root) {
    //利用栈进行每层节点的排列
    Stack<TreeNode> stack = new Stack<>();
    Stack<TreeNode> temp = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            System.out.print(pop.val+" ");
            if (pop.left != null) temp.push(pop.left);
            if (pop.right != null) temp.push(pop.right);
        }
        while (!temp.isEmpty()) {
            stack.push(temp.pop());
        }
    }
}

前序遍历

   
 public static void pre(TreeNode root) {
        if (root == null) return;
        System.out.print(root.val+" ");
        if (root.left != null) pre(root.left);
        if (root.right != null) pre(root.right);
    }

中序遍历

public static void mid(TreeNode root) {
    if (root == null) return;
    if (root.left != null) mid(root.left);
    System.out.print(root.val+" ");
    if (root.right != null) mid(root.right);
}

后序遍历

public static void after(TreeNode root) {
    if (root == null) return;
    if (root.left != null) after(root.left);
    if (root.right != null) after(root.right);
    System.out.print(root.val+" ");
}

  • 15
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值