求二叉樹最大寬度



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;
}

}

}

/* 如有意見或建議,歡迎評論區留言;如發現代碼有誤,歡迎批評指正 */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM