|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(h) |
| 3 | + |
| 4 | +/** |
| 5 | + * Definition for a binary tree node. |
| 6 | + * struct TreeNode { |
| 7 | + * int val; |
| 8 | + * TreeNode *left; |
| 9 | + * TreeNode *right; |
| 10 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 11 | + * }; |
| 12 | + */ |
| 13 | +class Solution { |
| 14 | +public: |
| 15 | + vector<int> boundaryOfBinaryTree(TreeNode* root) { |
| 16 | + if (!root) { |
| 17 | + return {}; |
| 18 | + } |
| 19 | + |
| 20 | + vector<int> nodes; |
| 21 | + nodes.emplace_back(root->val); |
| 22 | + leftBoundary(root->left, &nodes); |
| 23 | + leaves(root->left, &nodes); |
| 24 | + leaves(root->right, &nodes); |
| 25 | + rightBoundary(root->right, &nodes); |
| 26 | + return nodes; |
| 27 | + } |
| 28 | + |
| 29 | +private: |
| 30 | + void leftBoundary(TreeNode *root, vector<int> *nodes) { |
| 31 | + if (!root || (!root->left && !root->right)) { |
| 32 | + return; |
| 33 | + } |
| 34 | + nodes->emplace_back(root->val); |
| 35 | + if (!root->left) { |
| 36 | + leftBoundary(root->right, nodes); |
| 37 | + } else { |
| 38 | + leftBoundary(root->left, nodes); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + void rightBoundary(TreeNode *root, vector<int> *nodes) { |
| 43 | + if (!root || (!root->right && !root->left)) { |
| 44 | + return; |
| 45 | + } |
| 46 | + if (!root->right) { |
| 47 | + rightBoundary(root->left, nodes); |
| 48 | + } else { |
| 49 | + rightBoundary(root->right, nodes); |
| 50 | + } |
| 51 | + nodes->emplace_back(root->val); |
| 52 | + } |
| 53 | + |
| 54 | + void leaves(TreeNode *root, vector<int> *nodes) { |
| 55 | + if (!root) { |
| 56 | + return; |
| 57 | + } |
| 58 | + if (!root->left && !root->right) { |
| 59 | + nodes->emplace_back(root->val); |
| 60 | + return; |
| 61 | + } |
| 62 | + leaves(root->left, nodes); |
| 63 | + leaves(root->right, nodes); |
| 64 | + } |
| 65 | +}; |
0 commit comments