程序员人生 网站导航

Java数据结构系列之――树(4):二叉树的中序遍历的递归与非递归实现

栏目:php教程时间:2014-12-22 08:36:22
package tree.binarytree; import java.util.Stack; /** * 2叉树的中序遍历:递归与非递归实现 * * @author wl * */ public class BiTreeInOrder { // 中序遍历的递归实现 public static void biTreeInOrderByRecursion(BiTreeNode root) { if (root == null) { return; } biTreeInOrderByRecursion(root.leftNode); System.out.println(root.data); biTreeInOrderByRecursion(root.rightNode); } // 中序遍历的非递归实现 public static void biTreeInOrder(BiTreeNode root) { Stack<BiTreeNode> stack = new Stack<BiTreeNode>();// 栈,用于寄存2叉树的结点 BiTreeNode current = root;// 当前结点 while (current != null || !stack.empty()) { while (current != null) { stack.push(current); current = current.leftNode; } if (!stack.empty()) { current = stack.pop(); System.out.println(current.data); current = current.rightNode; } } } }

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐