二叉树的递归遍历
来源:互联网 发布:淘宝客活动广场有用吗 编辑:程序博客网 时间:2024/06/11 08:37
先序遍历(先根遍历):首先访问根结点然后遍历左子树,最后遍历右子树。在遍历左、右子树时,仍然先访问根结点,然后遍历左子树,最后遍历右子树。
中序遍历:首先遍历左子树,然后访问根结点,最后遍历右子树。在遍历左、右子树时,仍然先遍历左子树,再访问根结点,最后遍历右子树。
后序遍历:后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。
定义并构造二叉树如下:
public class BinaryTree {int root; // 根节点BinaryTree left; // 左子树BinaryTree right; // 右子树public BinaryTree(int root) {this.root = root;left = null;right = null;}//递归构造二叉树,左节点小于根节点,右节点大于根节点public void builTree(BinaryTree tree, int root) {if (root > tree.root) {if (tree.right == null) {tree.right = new BinaryTree(root);} else {this.builTree(tree.right, root);}} else {if (tree.left == null) {tree.left = new BinaryTree(root);} else {this.builTree(tree.left, root);}}}}
实例化二叉树并遍历:
public class BinaryTreePreorder {public static void main(String[] str) {int[] array = { 5, 3, 2, 1, 4, 8, 7, 6, 10, 9 };BinaryTree tree = new BinaryTree(array[0]); // 创建二叉树,初始化根节点for (int i = 1; i < array.length; i++) {tree.builTree(tree, array[i]); // 构造二叉树}System.out.println("先根遍历:");preOrder(tree);System.out.println();System.out.println("中根遍历:");inOrder(tree);System.out.println();System.out.println("后根遍历:");postOrder(tree);}public static void preOrder(BinaryTree tree) { // 先序遍历if (tree != null) {System.out.print(tree.root + "-");preOrder(tree.left);preOrder(tree.right);}}public static void inOrder(BinaryTree tree) { // 中序遍历if (tree != null) {inOrder(tree.left);System.out.print(tree.root + "-");inOrder(tree.right);}}public static void postOrder(BinaryTree tree) { // 后序遍历if (tree != null) {postOrder(tree.left);postOrder(tree.right);System.out.print(tree.root + "-");}}}二叉树的结构如下:
输出结果如下:
0 0
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的遍历(递归)
- 二叉树的先中后序遍历,递归遍历,非递归遍历
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 字符数组、字符串与string类的区别
- 配置mysql5.5主从服务器
- KVC中setValuesForKeysWithDictionary:
- wget命令
- N-Queens II
- 二叉树的递归遍历
- GRE词汇备考:不同阶段该如何背单词?
- 文件存储的选择
- Linux自动删除tomcat日志文件
- 数学-矩阵计算(2)矩阵函数微积分前奏
- 不翻墙更新Android 5.0 SDK
- 用fiddler2抓ios http包
- 参数传递三种方式
- poj 1948 二维01背包