Java基础 - 二叉树的遍历之深度优先遍历(非递归遍历)

package com.yc.test;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

import com.yc.tree.ThreeLinkBinTree;
import com.yc.tree.ThreeLinkBinTree.Node;

/**
 * 
 * @author wb
 *下面以三叉链表结构的二叉树为例实现这三种遍历:
 */	
public class DFS {
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public static void main(String[] args) {
		ThreeLinkBinTree<String> tree = new ThreeLinkBinTree<String>("A");
		Node n2_l = tree.addAndReturn(tree.root(), "+", true);
		Node n2_r = tree.addAndReturn(tree.root(), "B", false);

		Node n3_n2_l = tree.addAndReturn(n2_l, "*", true);
		Node n3_n2_r = tree.addAndReturn(n2_l, "D", false);

		Node n4_n3_n2_l = tree.addAndReturn(n3_n2_l, "/", true);
		Node n4_n3_n2_r = tree.addAndReturn(n3_n2_l, "%", false);

		Node n5_n4_n3_n2_l = tree.addAndReturn(n4_n3_n2_r, "E", true);
		Node n5_n4_n3_n2_r = tree.addAndReturn(n4_n3_n2_r, "F", false);

		/**
		 * 此时二叉树的情况为:
		 * 						   A
		 * 					         │ │
		 * 					     + ←┘ └→ B
		 * 					   │ │	
		 * 				       * ←┘ └→ D
		 * 				     │ │
		 * 				 / ←┘ └→ %
		 * 					   │ │
		 * 				       E ←┘ └→ F
		 * 
		 */

		System.out.println( "非递归先序遍历结果:" + cStackDLR(tree));

		System.out.println( "非递归中序遍历结果:" + cStackLDR(tree));
		
		System.out.println( "非递归后序遍历结果:" + cStackLRD(tree));

	}


	//非递归方式前序遍历
	public static List<Node> cStackDLR(ThreeLinkBinTree<String> tree){
		return stackDLR(tree.root());
	}
	private static List<Node> stackDLR(Node node) {
		//用于返回的
		List<Node> nodes = new ArrayList<Node>();
		//用于操作的(在前面的几章中讲到Deque继承了 Queue和Stack俩个接口或者类,所以它具有队列和栈的特性)
		Deque<Node> deque = new ArrayDeque<Node>();

		deque.push(node);

		mainDealForDFS(deque, nodes);

		return nodes;
	}

	//非递归方式中序遍历
	public static List<Node> cStackLDR(ThreeLinkBinTree<String> tree){
		return stackLDR(tree.root());
	}
	private static List<Node> stackLDR(Node node) {
		//用于返回的
		List<Node> nodes = new ArrayList<Node>();
		//用于操作的(在前面的几章中讲到Deque继承了 Queue和Stack俩个接口或者类,所以它具有队列和栈的特性)
		Deque<Node> deque = new ArrayDeque<Node>();

		Node rootLeftChild = node.getLeft();
		Node rootRightChild = node.getRight();

		deque.push(rootLeftChild);
		mainDealForDFS(deque, nodes);

		nodes.add(node);

		deque.push(rootRightChild);
		mainDealForDFS(deque, nodes);

		return nodes;
	}

	//非递归方式后序遍历
	public static List<Node> cStackLRD(ThreeLinkBinTree<String> tree){
		return stackLRD(tree.root());
	}
	private static List<Node> stackLRD(Node node) {
		//用于返回的
		List<Node> nodes = new ArrayList<Node>();
		//用于操作的(在前面的几章中讲到Deque继承了 Queue和Stack俩个接口或者类,所以它具有队列和栈的特性)
		Deque<Node> deque = new ArrayDeque<Node>();

		Node rootLeftChild = node.getLeft();
		Node rootRightChild = node.getRight();

		deque.push(rootLeftChild);
		mainDealForDFS(deque, nodes);

		deque.push(rootRightChild);
		mainDealForDFS(deque, nodes);

		nodes.add(node);
		
		return nodes;
	}
	private static void mainDealForDFS(Deque<Node> deque, List<Node> nodes){
		while(!deque.isEmpty()){
			//移除栈顶节点并添加到nodes里
			Node tempN = deque.pop();
			nodes.add( tempN);

			if(tempN != null){
				if(tempN.getRight() != null){
					deque.push( tempN.getRight());
				}
				if(tempN.getLeft() != null){

					deque.push( tempN.getLeft());
				}
			}
		}
	}
}

 

测试结果为:

 

 

非递归先序遍历结果:[A, +, *, /, %, E, F, D, B]
非递归中序遍历结果:[+, *, /, %, E, F, D, A, B]
非递归后序遍历结果:[+, *, /, %, E, F, D, B, A]

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现二叉树深度优先可以使用归或者栈来实现。归方法比较简单,可以按照先序遍、中序遍和后序遍的方式进行深度优先。下面是一段示例代码,演示了Java中使用归实现深度优先的方法: ``` public class BinaryTree { // 定义二叉树节点类 public class TreeNode { public TreeNode leftNode; public TreeNode rightNode; public Integer val; public TreeNode(Integer val) { this.val = val; } } // 深度优先-先序遍 public void startErgodic(TreeNode node) { if (node == null) { return; } System.out.print(node.val + " "); startErgodic(node.leftNode); startErgodic(node.rightNode); } // 深度优先-中序遍 public void midErgodic(TreeNode node) { if (node == null) { return; } midErgodic(node.leftNode); System.out.print(node.val + " "); midErgodic(node.rightNode); } // 深度优先-后序遍 public void endErgodic(TreeNode node) { if (node == null) { return; } endErgodic(node.leftNode); endErgodic(node.rightNode); System.out.print(node.val + " "); } // 二叉树的插入操作 public void insert(Integer val) { // 插入操作的具体实现代码 } // 二叉树归插入操作 public void insertDigui(Integer val, TreeNode node) { // 归插入操作的具体实现代码 } // 广度优先遍 public void Order() { // 广度优先遍的具体实现代码 } } public class Test { public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); // 创建二叉树并进行插入操作 // 深度优先-先序遍 binaryTree.startErgodic(binaryTree.root); System.out.println(); // 深度优先-中序遍 binaryTree.midErgodic(binaryTree.root); System.out.println(); // 深度优先-后序遍 binaryTree.endErgodic(binaryTree.root); } } ``` 上述代码中的`startErgodic()`方法实现了二叉树深度优先先序遍,`midErgodic()`方法实现了中序遍,`endErgodic()`方法实现了后序遍。可以根据需要选择相应的方法进行遍。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java实现二叉树深度优先和广度优先遍算法示例](https://download.csdn.net/download/weixin_38518885/12761000)[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* *3* [java有序二叉树深度优先和广度优先遍](https://blog.csdn.net/m566666/article/details/122280365)[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、付费专栏及课程。

余额充值