Maximum Width of Binary Tree问题及解法

问题描述:

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.

示例:

Input: 

           1
         /   \
        3     2
       / \     \  
      5   3     9 

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

          1
         /  
        3    
       / \       
      5   3     

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

          1
         / \
        3   2 
       /        
      5      

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

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

问题分析:

题目主要考查节点编号问题,对于一个左子节点,其编号为父节点编号的两倍,而右子节点编号为父节点编号两倍加1.

最终遍历每层找到最左最右节点编号,取其中最大的差值加1即为答案。


过程详见代码:

/**
 * 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) {
		if (root == nullptr) return 0;
		int res = 0;
		vector<pair<int, int>> val;
		val.emplace_back(pair<int, int>(1, 1));
		dfs(root->left, val, 1, 1, 0);
		dfs(root->right, val, 1, 1, 1);
		for (auto v : val)
		{
			int  t = v.second - v.first + 1;
			if (t > res) res = t;
		}
		return res;
	}

	void dfs(TreeNode* root, vector<pair<int, int>>& val, int depth, int parent, int dirt)
	{
		if (root == nullptr) return;
		if (val.size() <= depth) val.emplace_back(pair<int, int>(parent * 2 + dirt, parent * 2 + dirt));
		else val[depth].second = parent * 2 + dirt;
		dfs(root->left, val, depth + 1, parent * 2 + dirt, 0);
		dfs(root->right, val, depth + 1, parent * 2 + dirt, 1);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值