Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
boundary-of-binary-tree.cpp 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-04-01 17:32 +08:00 . Create boundary-of-binary-tree.cpp
// 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:
vector<int> boundaryOfBinaryTree(TreeNode* root) {
if (!root) {
return {};
}
vector<int> nodes;
nodes.emplace_back(root->val);
leftBoundary(root->left, &nodes);
leaves(root->left, &nodes);
leaves(root->right, &nodes);
rightBoundary(root->right, &nodes);
return nodes;
}
private:
void leftBoundary(TreeNode *root, vector<int> *nodes) {
if (!root || (!root->left && !root->right)) {
return;
}
nodes->emplace_back(root->val);
if (!root->left) {
leftBoundary(root->right, nodes);
} else {
leftBoundary(root->left, nodes);
}
}
void rightBoundary(TreeNode *root, vector<int> *nodes) {
if (!root || (!root->right && !root->left)) {
return;
}
if (!root->right) {
rightBoundary(root->left, nodes);
} else {
rightBoundary(root->right, nodes);
}
nodes->emplace_back(root->val);
}
void leaves(TreeNode *root, vector<int> *nodes) {
if (!root) {
return;
}
if (!root->left && !root->right) {
nodes->emplace_back(root->val);
return;
}
leaves(root->left, nodes);
leaves(root->right, nodes);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助