leetcode 662. Maximum Width of Binary Tree | 662. 二叉树最大宽度(BFS)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 662. Maximum Width of Binary Tree | 662. 二叉树最大宽度(BFS)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/maximum-width-of-binary-tree/
題解
本題思路來源于二叉樹的層序遍歷。
- 層序遍歷類似問題:leetcode 199. Binary Tree Right Side View | 199. 二叉樹的右視圖(Java)
- 如何使用“記錄下一行最右節(jié)點(diǎn)”的方式,進(jìn)行層序遍歷:左神算法:二叉樹的按層打印與ZigZag打印
一開始就想到了給每一個(gè)元素維護(hù) position,但誤以為 左孩子 pos-1,右孩子 pos+1,提交之后才發(fā)現(xiàn)并不是這樣的。看了下答案的提示:
答案
這個(gè)問題中的主要想法是,利用完全二叉樹(用數(shù)組存儲(chǔ)堆)的性質(zhì),給每個(gè)節(jié)點(diǎn)一個(gè) position 值,如果我們走向左子樹,那么 position -> position * 2,如果我們走向右子樹,那么 position -> positon * 2 + 1。當(dāng)我們?cè)诳赐粚由疃鹊奈恢弥?L 和 R 的時(shí)候,寬度就是 R - L + 1。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/ class Info {TreeNode node;int index;public Info(TreeNode node, int index) {this.node = node;this.index = index;} }class Solution {public int widthOfBinaryTree(TreeNode root) {Queue<Info> queue = new LinkedList<>();Info nextLast = new Info(root, 0);Info curFirst = nextLast;Info curLast = nextLast;queue.add(nextLast);int result = 0;while (queue.size() > 0) {Info poll = queue.poll();if (poll.node.left != null) {Info left = new Info(poll.node.left, poll.index * 2);queue.offer(left);nextLast = left;}if (poll.node.right != null) {Info right = new Info(poll.node.right, poll.index * 2 + 1);queue.offer(right);nextLast = right;}if (poll.node == curLast.node) { // after this node, goto a new lineresult = Math.max(result, curLast.index - curFirst.index + 1);curFirst = queue.peek();curLast = nextLast;}}return result;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 662. Maximum Width of Binary Tree | 662. 二叉树最大宽度(BFS)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 650. 2 Keys
- 下一篇: Why docker command n