1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
與超過 1200 萬 開發者一起發現、參與優秀開源項目,私有倉庫也完全免費 :)
免費加入
文件
克隆/下載
maximum-width-of-binary-tree.cpp 848 Bytes
一鍵複製 編輯 原始數據 按行查看 歷史
// Time: O(n)
// Space: O(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) {
vector<int> leftmosts;
return dfs(root, 1, 0, &leftmosts);
}
private:
int dfs(TreeNode* node, int id, int depth, vector<int> *leftmosts) {
if (!node) {
return 0;
}
if (depth >= leftmosts->size()) {
leftmosts->emplace_back(id);
}
int result = id - (*leftmosts)[depth] + 1;
result = max(result, dfs(node->left, id * 2, depth + 1, leftmosts));
result = max(result, dfs(node->right, id * 2 + 1, depth + 1, leftmosts));
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索幫助