zoukankan      html  css  js  c++  java
  • 打印二叉树的所有最右节点

    解法:使用按层遍历二叉树的非递归形式
    每次到达此层末尾时就打印。

    public class PrintTreeRightNode {
    public static class Node{
    private Node left;
    private Node right;
    private int value;
    public Node(int value){
    this.value = value;
    }
    }
    //按层遍历使用队列。
    public void printTreeRightNode(Node head){
    if(head==null){
    return ;
    }
    Queue<Node> queue = new ArrayDeque<>();
    queue.add(head);
    int start = 0;//设置一层的开始位置
    int end = 1; //设置一层的结束位置
    while (!queue.isEmpty()){
    Node node = queue.poll();
    start++;
    if(node.left!=null){ //添加左孩子
    queue.add(node.left);
    }
    if(node.right!=null){ //添加右孩子
    queue.add(node.right);
    }
    if(start==end){ //当到达末尾时
    start = 0;
    end = queue.size();//这层完事时,因为存的都是下一层的孩子,所以队列的大小就是孩子的个数。
    System.out.print(queue.peek());
    }
    }
    }
    }
    总结:按层遍历二叉树的变形。
  • 相关阅读:
    自动化测试初介
    接口测试初介
    常见测试面试过程及及问题解析
    hadoop伪分布式平台组件搭建
    使用Github搭建个人博客
    centos7中redis安装配置
    Hive安装配置
    hadoop大数据组件启动
    Java生成窗口
    正则语法
  • 原文地址:https://www.cnblogs.com/liuwentao/p/9484569.html
Copyright © 2011-2022 走看看