二叉树遍历

一、前序遍历:根 -> 左 -> 右
1、以递归的方式前序遍历二叉树
public static void preorderByRecursion(TreeNode root, List<Integer> list) {
	if (root == null) {
	   return;
	}
	list.add(root.value);
	preorderByRecursion(root.left, list);
	preorderByRecursion(root.right, list);
}
2、以栈的方式前序遍历二叉树
public static void preorderByStack(TreeNode root, List<Integer> list) {
    Stack<TreeNode> stack = new Stack<>();
    while (root != null || !stack.empty()) {
        while (root != null) {
            list.add(root.value);
            stack.push(root);
            root = root.left;
        }
        if (!stack.empty()) {
            root = stack.pop().right;
        }
    }
}
二、中序遍历:左 -> 根 -> 右
1、以递归的方式中序遍历二叉树
public static void inorderByRecursion(TreeNode root, List<Integer> list) {
    if (root == null) {
        return;
    }
    inorderByRecursion(root.left, list);
    list.add(root.value);
    inorderByRecursion(root.right, list);
}
2、以栈的方式中序遍历二叉树
public static void inorderByStack(TreeNode root, List<Integer> list) {
    Stack<TreeNode> stack = new Stack<>();
    while (root != null || !stack.empty()) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
        if (!stack.empty()) {
            root = stack.pop();
            list.add(root.value);
            root = root.right;
        }
    }
}
三、后序遍历:左 -> 右 -> 根
1、以递归的方式后序遍历二叉树
public static void postorderByRecursion(TreeNode root, List<Integer> list) {
    if (root == null) {
        return;
    }
    postorderByRecursion(root.left, list);
    postorderByRecursion(root.right, list);
    list.add(root.value);
}
2、以栈的方式后序遍历二叉树
public static void postorderByStackInRight(TreeNode root, List<Integer> list) {
    Stack<TreeNode> nodeStack = new Stack<>();
    Stack<Integer> resultStack = new Stack<>();
    while (root != null || !nodeStack.empty()) {
        while (root != null) {
            nodeStack.push(root);
            resultStack.push(root.value);
            root = root.right;
        }
        if (!nodeStack.empty()) {
            root = nodeStack.pop().left;
        }
    }
    while (!resultStack.empty()) {
        list.add(resultStack.pop());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值