[leetcode] 662. Maximum Width of Binary Tree

网友投稿 692 2022-08-23

[leetcode] 662. Maximum Width of Binary Tree

[leetcode] 662. Maximum Width of Binary Tree

Description

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

Input: 1 / \ 3 2 / \ \ 5 3 9 Output: 4Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: 1 / 3 / \ 5 3 Output: 2Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: 1 / \ 3 2 / 5 Output: 2Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input: 1 / \ 3 2 / \ 5 9 / \ 6 7Output: 8Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

Note: Answer will in the range of 32-bit signed integer.

分析

题目的意思是:求一个二叉树的最大宽度。

对于一棵完美二叉树,如果根结点是深度1,那么每一层的结点数就是2n-1,那么每个结点的位置就是[1, 2n-1]中的一个,假设某个结点的位置是i,那么其左右子结点的位置可以直接算出来,为2i和2i+1。我们从根结点进入,深度为0,位置为1,进入递归函数。首先判断,如果当前结点为空,那么直接返回,然后判断如果当前深度大于start数组的长度,说明当前到了新的一层的最左结点,我们将当前位置存入start数组中。然后我们用idx - start[h] + 1来更新结果res。这里idx是当前结点的位置,start[h]是当前层最左结点的位置。然后对左右子结点分别调用递归函数,注意左右子结点的位置可以直接计算出来。

代码

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int widthOfBinaryTree(TreeNode* root) { int res=0; vector start; solve(root,0,1,start,res); return res; } void solve(TreeNode* root,int h,int idx,vector& start,int& res){ if(!root){ return ; } if(h>=start.size()) start.push_back(idx); res=max(res,idx-start[h]+1); solve(root->left,h+1,idx*2,start,res); solve(root->right,h+1,idx*2+1,start,res); }};

参考文献

​​[LeetCode] Maximum Width of Binary Tree 二叉树的最大宽度​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android 多线程编程的总结(android是什么系统)
下一篇:python plotly绘制Choropleth 地图
相关文章

 发表评论

暂时没有评论,来抢沙发吧~