• 树的深度优先遍历,广度优先遍历


    package com.lkr.dataStructure;

    //import javax.swing.tree.TreeNode;
    import java.util.ArrayDeque;
    //import com.lkr.dataStructure.TreeNode;

    public class TreeBianli {

    public static void main(String[] args){
    TreeNode root = new TreeNode(1);
    TreeNode secondNode = new TreeNode(2);
    TreeNode thirdNode = new TreeNode(3);
    TreeNode forthNode = new TreeNode(4);
    TreeNode fifthNode = new TreeNode(5);
    TreeNode sixthNode = new TreeNode(6);
    TreeNode seventhNode = new TreeNode(7);
    root.right = secondNode;
    root.left = thirdNode;
    secondNode.right = forthNode;
    secondNode.left = fifthNode;
    thirdNode.right = sixthNode;
    sixthNode.left = seventhNode;

    System.out.println("深度优先遍历结果: ");
    new TreeBianli().depthOrderTraversal(root);

    System.out.println("广度优先遍历结果: ");
    new TreeBianli().levelOrderTraversal(root);

    }
    //深度优先算法采用栈来实现非递归算法
    public void depthOrderTraversal(TreeNode root){
    if(root==null){
    System.out.println("empty tree");
    return;
    }
    ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
    stack.push(root);
    while (stack.isEmpty()==false){
    TreeNode node = stack.pop();
    System.out.print(node.value+" ");
    if(node.right != null){
    stack.push(node.right);
    }
    if(node.left != null){
    stack.push(node.left);
    }
    }
    System.out.print(" ");
    }

    //广度优先算法利用队列来实现非递归算法
    public void levelOrderTraversal(TreeNode root){
    if(null==root){
    System.out.println("empth tree");
    return;
    }
    ArrayDeque<TreeNode> queue = new ArrayDeque<>();
    queue.add(root);
    while(queue.isEmpty()== false){
    TreeNode node = queue.remove();
    System.out.print(node.value + " ");
    if(null != node.left){
    queue.add(node.left);
    }
    if(null != node.right){
    queue.add(node.right);
    }
    }
    System.out.print(" ");
    }
    }
  • 相关阅读:
    浅析HSTS
    浅析Diffie–Hellman
    SSIM(结构相似度算法)不同实现版本的差异
    某直播App问题分析
    相机与摄影基础
    Macaca-iOS入门那些事2
    Macaca-iOS入门那些事
    iOS instruments trace文件解析方案
    关于QCon2015感想与反思
    深入浅出Android App耗电量统计
  • 原文地址:https://www.cnblogs.com/turningli/p/10393675.html
Copyright © 2020-2023  润新知