zoukankan      html  css  js  c++  java
  • 采用递归方式遍历二叉树

    public class BinaryTree {
    
        public static void main(String[] args) {
            
            Node root = new Node(1);
            root.left = new Node(2);
            root.right = new Node(3);
            root.left.left = new Node(4);
            root.left.right = new Node(5);
            root.right.left = new Node(6);
            root.right.right = new Node(7);
            print(root);
            
        }
    
        /**
         * 先序遍历:访问根结点的操作发生在遍历其左右子树之前。  根节点 -> 左子树 -> 右子树             1 2 4 5 3 6 7    
         * 中序遍历:访问根结点的操作发生在遍历其左右子树中间。  左子树 -> 根节点 -> 右子树             4 2 5 1 6 3 7 
         * 后序遍历:访问根结点的操作发生在遍历其左右子树之后。  左子树 -> 右子树 -> 根节点             4 5 2 6 7 3 1 
         * 
         */
        public static void print(Node root) {
            if (root == null) {
                return;
            }
            // 先序遍历,这行是第一次来到该节点
    //        System.out.print(root.value + " ");
            print(root.left);
            // 中序遍历,这行是第二次来到该节点
    //        System.out.print(root.value + " ");
            print(root.right);
            // 后序遍历,这行是第三次来到该节点
            System.out.print(root.value + " ");
        }
    
        public static class Node {
            Node left;
            Node right;
            int value;
    
            public Node(int value) {
                this.value = value;
            }
    
        }
    }
  • 相关阅读:
    与MS Project相关的两个项目
    最后的报告bug
    oo第二阶段的总结
    第一阶段的反思和改变
    面向对象设计与构造第四次课程总结
    面向对象设计与构造第三次课程总结
    面向对象设计与构造第一次课程总结
    OO游记之六月篇
    OO游记之五月篇
    OO游记之四月篇
  • 原文地址:https://www.cnblogs.com/moris5013/p/11648788.html
Copyright © 2011-2022 走看看