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;
            }
    
        }
    }
  • 相关阅读:
    牛顿迭代法
    C语言补遗
    Manjaro添加开机启动脚本
    tensorboard查看pytorch模型
    Kindle最佳排版记录
    01背包问题详解
    差分法介绍
    BFS详解
    UVA11732 "strcmp()" Anyone?
    LA3942 Remember the Word
  • 原文地址:https://www.cnblogs.com/moris5013/p/11648788.html
Copyright © 2011-2022 走看看