Try   HackMD

545. Boundary of Binary Tree


My Solution

The Key Idea for Solving This Coding Question

C++ Code

/** * 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