给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
示例 1:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
示例 2:
输入:
1
/
3
/ \
5 3
输出: 2
解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
示例 3:
输入:
1
/ \
3 2
/
5
输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
示例 4:
输入:
1
/ \
3 2
/ \
5 9
/ \
6 7
输出: 8
解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
注意: 答案在32位有符号整数的表示范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行用时 :8 ms, 在所有 C 提交中击败了54.55%的用户
内存消耗 :8.3 MB, 在所有 C 提交中击败了57.14%的用户
花了3个小时, 还是峰回路转啊!
struct ChainNode{
struct TreeNode *node;
unsigned long long value;
struct ChainNode *next;
};
struct ChainNode *createChainNodeHead(){
struct ChainNode *chainNode = malloc(sizeof(struct ChainNode));
if (!chainNode) {
return NULL;
}
chainNode->next = NULL;
chainNode->node = NULL;
return chainNode;
}
struct ChainNode *createChainNode(struct ChainNode *father,struct TreeNode *node){
struct ChainNode *chainNode = malloc(sizeof(struct ChainNode));
if (!chainNode) {
return NULL;
}
if (father) {
father->next = chainNode;
}
chainNode->node = node;
chainNode->next = NULL;
return chainNode;
}
int widthOfBinaryTree(struct TreeNode* root){
// printNode(root, 1);
struct ChainNode *head = createChainNodeHead();
struct ChainNode *chainTailNode = head;
chainTailNode = createChainNode(chainTailNode, root);
chainTailNode->value = 0l;
unsigned long long maxDistance = 1;
while (head->next) {
struct ChainNode *chainNode = head->next;
head->next = NULL;
chainTailNode = head;
unsigned long long beginNum = chainNode->value;
unsigned long long number = 1;
struct ChainNode *tmpChainNode = NULL;
while (chainNode) {
struct TreeNode *treeNode = chainNode->node;
// printf("val:%ld - %ld \n",chainNode->value, beginNum);
number = chainNode->value - beginNum +1;
if(treeNode->left){
chainTailNode =createChainNode(chainTailNode, treeNode->left);
chainTailNode->value = chainNode->value*2+1;
// printf("l->%d ",treeNode->left->val);
}
if (treeNode->right) {
chainTailNode =createChainNode(chainTailNode, treeNode->right);
chainTailNode->value = chainNode->value*2+2;
// printf("r-%d ",treeNode->right->val);
}
tmpChainNode = chainNode;
chainNode = chainNode->next;
free(tmpChainNode);
}
// printf("num: %ld\n",number);
maxDistance = maxDistance>number ? maxDistance: number;
}
free(head);
return (int)maxDistance;
}
struct TreeNode *createNode(int val,struct TreeNode* nodeL,struct TreeNode* nodeR){
struct TreeNode *node = malloc(sizeof(struct TreeNode));
if (!node) {
assert(0);
}
node->val = val;
node->left = nodeL;
node->right = nodeR;
return node;
}
网友评论