/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> boundaryOfBinaryTree(TreeNode *root) {
vector<int> boundary;
boundary.push_back(root->val);
if (root->left != nullptr) {
leftBoundary(root->left, boundary);
}
if (root->left != nullptr || root->right != nullptr) {
bottomBoundary(root, boundary);
}
if (root->right != nullptr) {
rightBoundary(root->right, boundary);
}
return boundary;
}
private:
void leftBoundary(TreeNode *root, vector<int> &boundary) {
if (root == nullptr ||
(root->left == nullptr && root->right == nullptr)) {
return;
}
boundary.push_back(root->val);
if (root->left != nullptr) {
leftBoundary(root->left, boundary);
return;
}
leftBoundary(root->right, boundary);
}
void bottomBoundary(TreeNode *root, vector<int> &boundary) {
if (root == nullptr) {
return;
}
if (root->left == nullptr && root->right == nullptr) {
boundary.push_back(root->val);
}
bottomBoundary(root->left, boundary);
bottomBoundary(root->right, boundary);
}
void rightBoundary(TreeNode *root, vector<int> &boundary) {
if (root == nullptr ||
(root->left == nullptr && root->right == nullptr)) {
return;
}
if (root->right != nullptr) {
rightBoundary(root->right, boundary);
boundary.push_back(root->val);
return;
}
rightBoundary(root->left, boundary);
boundary.push_back(root->val);
}
};
root
.
root
.