zoukankan      html  css  js  c++  java
  • 树的深度优先遍历,广度优先遍历

    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(" ");
    }
    }
  • 相关阅读:
    vs.net 2005, 没有找到MSVCR80D.dll的完美解决方案
    C++内存布局从一个修改私有变量的问题想到的
    堆栈详解
    加载.x文件
    深入分析规则引擎
    高级着色语言HLSL入门(5)
    字符数组,字符指针,Sizeof总结
    C++ 隐式和显式 初始化,类型转换
    fread()和fwrite()函数分析
    结构体 对齐的问题
  • 原文地址:https://www.cnblogs.com/turningli/p/10393675.html
Copyright © 2011-2022 走看看