集册 Java实例教程 二叉树级旅行算法

二叉树级旅行算法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

499
二叉树级旅行算法
//from 时 代 J a v a - nowjava.com

import java.util.*;


public class Algorithm_binaryTreeLevelTravel{

    public static void main(String[] args){

    

        TreeNode root = new TreeNode(0);


    }

    public static void recurisionTravel(TreeNode root,int level){

        if(root==null)

            return;

        else if(level==0)

            System.out.println(root.val);

        else{

            recurisionTravel(root.left,level-1);

            recurisionTravel(root.right,level-1);

        }

        

    }



    public void iteratorTravel(TreeNode root){//来自 nowjava - 时  代  Java

        Queue<TreeNode> queue = new LinkedList<TreeNode>();// an empty LinkedList.  

        queue.offer(root);

        TreeNode node = new TreeNode();

        queue.offer(node);

        // poll()&offer() will return null or false, if the queue is empty or is full(for a capability-restricted)

        while(queue.peek()!=null) {

            TreeNode node = queue.poll();

            System.out.println(node.val());

            queue.offer(node.left);

            queue.offer(node.right);

        }

    }

}


class TreeNode{

   
展开阅读全文