---
tags: leetcode
---
# [545. Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
/**
* 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);
}
};
```
## Time Complexity
$O(n)$
$n$ is the number of nodes in the binary tree referred by `root`.
## Space Complexity
$O(H)$
$H$ is the height of the binary tree referred by `root`.
# Miscellane
<!--
# Test Cases
```
[1,null,2,3,4]
```
```
[1,2,3,4,5,6,null,null,null,7,8,9,10]
```
```
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
```
* Wrong Answer
```
[3,1,null,null,2,4,null,5]
```
* Wrong Answer
```
[1]
```
* Wrong Answer
```
[1,null,4,3,null,2,null,5]
```
-->