zoukankan      html  css  js  c++  java
  • 求二叉树最大宽度


    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Queue;

    /**
    * 二叉树最大宽度
    */
    public class TreeMaxWidth {

    /**
    * 不使用HashMap实现
    *
    * @param head 二叉树的头节点
    * @return 最大宽度
    */
    public int treeMaxWidthNoMap(Node head) {
    int maxWidth = 0;
    if (head == null) {
    return maxWidth;
    }
    // 用队列实现
    Queue<Node> queue = new LinkedList<>();
    queue.add(head);
    Node curEnd = head;
    Node nextEnd = null;
    int curWidth = 0;
    while (!queue.isEmpty()) {
    Node node = queue.poll();
    if (node.left != null) {
    queue.add(node.left);
    nextEnd = node.left;
    }
    if (node.right != null) {
    queue.add(node.right);
    nextEnd = node.right;
    }
    curWidth++;
    if (node == curEnd) {
    maxWidth = Math.max(maxWidth, curWidth);
    curWidth = 0;
    curEnd = nextEnd;
    }
    }
    return maxWidth;
    }

    /**
    * 使用HashMap实现
    *
    * @param head 二叉树的头节点
    * @return 最大宽度
    */
    public int treeMaxWidthUseMap(Node head) {
    int maxWidth = 0;
    if (head == null) {
    return maxWidth;
    }
    // 用队列实现
    Queue<Node> queue = new LinkedList<>();
    queue.add(head);
    // 节点对应在哪一层
    HashMap<Node, Integer> levelMap = new HashMap<>();
    levelMap.put(head, 1);
    int curWidth = 0;
    int level = 1;
    while (!queue.isEmpty()) {
    Node node = queue.poll();
    int curLevel = levelMap.get(node);
    if (node.left != null) {
    queue.add(node.left);
    levelMap.put(node.left, levelMap.get(node) + 1);
    }
    if (node.right != null) {
    queue.add(node.right);
    levelMap.put(node.right, levelMap.get(node) + 1);
    }
    if (curLevel == level) {
    curWidth++;
    } else {
    maxWidth = Math.max(maxWidth, curWidth);
    level = curLevel;
    curWidth = 1;
    }
    }
    maxWidth = Math.max(maxWidth, curWidth);
    return maxWidth;
    }

    /**
    * 二叉树结构
    */
    public static class Node {

    public int value;

    public Node left;

    public Node right;

    public Node(int value) {
    this.value = value;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    HttpClient调用RestFul接口(post和get方式)
    mysql权限异常
    javascript:用法
    Java哈希值HashCode理解
    Java的CountDownLatch和CyclicBarrier的理解和区别
    Java并发编程与技术内幕:ThreadGroup线程组应用
    面试官: 谈谈什么是守护线程以及作用 ?
    java 成员变量 静态成员变量 方法 静态方法初始化顺序
    【java并发核心一】Semaphore 的使用思路
    threadlocal原理及常用应用场景
  • 原文地址:https://www.cnblogs.com/laydown/p/12946040.html
Copyright © 2011-2022 走看看