JAVA 二叉树遍历

二叉树的定义如下:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

递归的版本很简单,下面仅列出非递归的版本。

//先序遍历
public void searchPreOrder(TreeNode root) {
        Stack<TreeNode> s = new Stack<TreeNode>();
        if (root == null) {
            return;
        }
        while (root != null) {
            System.out.println(root.val);
            if (root.right != null) {
                s.push(root.right);
            }
            if (root.left != null) {
                root = root.left;
            } else {
                if (s.isEmpty()) {
                    break;
                }
                root = s.pop();
            }
        }

    }
//中序遍历
    public void searchMidOrder(TreeNode root) {
        Stack<TreeNode> s = new Stack<TreeNode>();
        while (root != null || (!s.isEmpty())) {
            while (root != null) {
                s.push(root);
                root = root.left;
            }
            if (!s.isEmpty()) {
                root = s.pop();
                System.out.print(root.val + " ");
                root = root.right;
            }
        }
    }
//后序遍历
    public void searchPostOrder(TreeNode root) {
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode t = null;
        int flag = 1;
        if (root == null) {
            return;
        }
        do {
            while (root != null) {
                s.push(root);
                root = root.left;
            }
            t = null;
            flag = 1;
            while ((!s.isEmpty()) && (flag == 1)) {
                root = s.peek();
                if (root.right == t) {
                    System.out.println(root.val);
                    t = root;
                    s.pop();
                } else {
                    root = root.right;
                    flag = 0;
                }
            }
        } while (!s.isEmpty());
    }
//层次遍历
public void levelSearch(TreeNode root) {
        Queue<TreeNode> s = new LinkedList<TreeNode>();
        if (root == null) {
            return;
        }
        s.add(root);
        while (!s.isEmpty()) {
            TreeNode t = s.poll();
            System.out.println(t.val);
            if (t.left != null) {
                s.add(t.left);
            }
            if (t.right != null) {
                s.add(t.right);
            }
        }
    }

在这做个记录,方便以后查阅。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值