日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二叉树最大宽度与leetcode662的二叉树最大宽度

發(fā)布時間:2024/4/18 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树最大宽度与leetcode662的二叉树最大宽度 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

首先先實現(xiàn)二叉樹的最大寬度,也就是某一層最多的節(jié)點個數(shù),使用了兩種方法,第一種是使用一個map數(shù)組盛放當(dāng)前節(jié)點以及當(dāng)前節(jié)點的層數(shù)。

public static int maxWidthUseMap(Node head) {if (head == null) {return 0;}Queue<Node> queue = new LinkedList<>();queue.add(head);// key 在 哪一層,valueHashMap<Node, Integer> levelMap = new HashMap<>();levelMap.put(head, 1);int curLevel = 1; // 當(dāng)前你正在統(tǒng)計哪一層的寬度int curLevelNodes = 0; // 當(dāng)前層curLevel層,寬度目前是多少int max = 0;while (!queue.isEmpty()) {Node cur = queue.poll();int curNodeLevel = levelMap.get(cur);if (cur.left != null) {levelMap.put(cur.left, curNodeLevel + 1);queue.add(cur.left);}if (cur.right != null) {levelMap.put(cur.right, curNodeLevel + 1);queue.add(cur.right);}if (curNodeLevel == curLevel) {curLevelNodes++;} else {max = Math.max(max, curLevelNodes);curLevel++;curLevelNodes = 1;//已經(jīng)有一個當(dāng)前節(jié)點了}}max = Math.max(max, curLevelNodes);return max;}

第二種方法是使用兩個linkedList,每一次倒空都代表著一層的結(jié)束:

private static int findMax(TreeNode node) {if (node == null) {return 0;}LinkedList<TreeNode> nodes = new LinkedList<>();LinkedList<TreeNode> cache = new LinkedList<>();int max = -1;nodes.add(node);while (true) {while (!nodes.isEmpty()) {//一次倒空的循環(huán)max = Math.max(nodes.size(), max);TreeNode poll = nodes.poll();if (poll.left != null) {cache.add(poll.left);}if (poll.right != null) {cache.add(poll.right);}}if (cache.size() == 0) {break;//如果此時下一層已經(jīng)沒有了就沒有必要繼續(xù)了,直接跳出循環(huán)}LinkedList<TreeNode> tmp = nodes;//進(jìn)行互換,這樣子此時的nodes就變成了下一層的所有nodesnodes = cache;cache = tmp;}return max;}

leetcode上的變種:

代碼實現(xiàn)如下,使用了while里面套一層for循環(huán),循環(huán)里面是存每一層的有節(jié)點的最左和最右下標(biāo)的,并且這里每一次for循環(huán)就是一層的循環(huán)結(jié)束:

private static int findMax(TreeNode node) {if (node == null) {return 0;}int max = 1;LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();LinkedList<Integer> list = new LinkedList<Integer>();list.add(0);nodes.offer(node);while(!nodes.isEmpty()){int count = nodes.size();for(;count>0;count--){TreeNode poll = nodes.poll();int curIndex = list.removeFirst();if(poll.left!=null){int left = curIndex*2+1;list.offer(left);nodes.offer(poll.left);}if(poll.right!=null){int right = curIndex*2+2;list.offer(right);nodes.offer(poll.right);}}if(list.size()>1){/// list 中 size 為 1 的情況下,寬度也為 1,沒有必要計算。max = Math.max(max,list.getLast()-list.getFirst()+1);}}return max; }

總結(jié)

以上是生活随笔為你收集整理的二叉树最大宽度与leetcode662的二叉树最大宽度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。