java实现二叉树的非递归遍历

二叉树的递归遍历写起来很简单,但是往往在面试中要写出它的非递归遍历,然而很多人都不能够写出来。结合网上的资料,自己写了一个完整的二叉树的前序遍历、中序遍历和后序遍历作为总结。

二叉树的测试用例如下:



public class FindPath_25 {
	
	public static void main(String []args) {
		BinaryTreeNode node1 = new BinaryTreeNode(10);
		BinaryTreeNode node2 = new BinaryTreeNode(5);
		BinaryTreeNode node3 = new BinaryTreeNode(12);
		BinaryTreeNode node4 = new BinaryTreeNode(4);
		BinaryTreeNode node5 = new BinaryTreeNode(7);
		
		node1.connection(node1, node2, node3);
		node1.connection(node2, node4, node5);

		System.out.println("先序遍历:");
		preOrder(node1);
		System.out.println();
		System.out.println("中序遍历:");
		inorder(node1);
		System.out.println();
		System.out.println("后序遍历:");
		postOrder(node1);
		System.out.println();
	}

	//非递归后序遍历
	private static void postOrder(BinaryTreeNode node1) {
		BinaryTreeNode q = node1;
        Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
        while (node1 != null) {
            // 左子树入栈
            while(node1!=null) {
            	stack.push(node1);
            	node1 = node1.left;
            }
            node1 = stack.pop();
            // 当前节点无右子结点或右子结点已经输出
            while (node1 != null && (node1.right == null || node1.right == q)) {
                System.out.print(node1.data+" ");
                q = node1;// 记录上一个已输出节点
                if (stack.empty())
                    return;
                node1 = stack.pop();
            }
            // 处理右子树
            stack.push(node1);
            node1 = node1.right;
        }		
	}

	//非递归中序遍历
	private static void inorder(BinaryTreeNode node1) {
		Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
        while(node1!=null||!stack.empty()) {
        	if(node1!=null) {
        		stack.push(node1);
        		node1 = node1.left;
        	}else {
        		node1 = stack.pop();
        		System.out.print(node1.data+" ");
        		node1 = node1.right;
        	}
        }
	}

	//非递归先序遍历
	private static void preOrder(BinaryTreeNode node1) {
		Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
        if (node1 != null) {
            stack.push(node1);
            while (!stack.empty()) {
            	node1 = stack.pop();
            	System.out.print(node1.data+" ");
                if (node1.right != null)
                    stack.push(node1.right);
                if (node1.left != null)
                    stack.push(node1.left);
            }
        }
	}

}

class BinaryTreeNode{
    int data;
    BinaryTreeNode left;
    BinaryTreeNode right;
    
    BinaryTreeNode(int data) {
    	this.data = data;
    	left = null;
    	right = null;
    }
    
    public void connection(BinaryTreeNode root,BinaryTreeNode left,BinaryTreeNode right) {
    	if(root == null) return;
    	root.left = left;
    	root.right = right;
    }
} 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java叉树归遍可以通过使用栈数据结构来实现。首先,我们创建一个空的栈,将根节点入栈。然后,我们进入一个循环,直到栈为空为止。在每一次循环中,我们弹出栈顶元素,并将其访问。接下来,如果该节点有右子节点,则将右子节点入栈。如果该节点有左子节点,则将左子节点入栈。由于栈是先进后出的数据结构,所以我们先入栈右子节点,再入栈左子节点,以确保在遍过程中先访问左子树节点。这样就能够实现叉树归遍。 以下是一个示例代码实现叉树归中序遍: ```java public void inorderTraversal(Node root) { if (root == null) { return; } Stack<Node> stack = new Stack<>(); Node current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.leftChild; } current = stack.pop(); System.out.print(current.data + " "); // 访问节点 current = current.rightChild; } } ``` 在这个示例代码中,我们首先判断当前节点是否为空或者栈是否为空,如果不满足则进入循环。在循环内部,我们首先将当前节点及其所有左子节点入栈,直到当前节点为空。然后,我们弹出栈顶节点并访问该节点。最后,将当前节点更新为其右子节点,并继续下一次循环。 通过这种方式,我们可以实现叉树归中序遍。你可以根据需要修改代码实现其他类型的归遍,比如前序遍和后序遍。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [用Python实现叉树、二叉树归遍及绘制的例子](https://download.csdn.net/download/weixin_38618784/14869891)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [java实现叉树树的归遍](https://blog.csdn.net/weixin_41826973/article/details/105555647)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值