Solution:
Need to get the left boundary, the right boundary, and the leaves. It is straightforward for the first two. For the last one, we need to the transverse of the tree. For simplicity, we can do it recursively. See code below:
/** * 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) { vector<int> l, res, r; if(!root) return l; l.push_back(root->val); TreeNode* p = root->left, *p1 = root->right; if(!p && !p1) return l; while(p){ if(p->left || p->right) l.push_back(p->val); if(p->left) p = p->left; else p = p->right; } while(p1){ if(p1->left || p1->right) r.push_back(p1->val); if(p1->right) p1 = p1->right; else p1 = p1->left; } help(res, root); reverse(res.begin(), res.end()); while(res.size()){ l.push_back(res.back()); res.pop_back(); } while(r.size()){ l.push_back(r.back()); r.pop_back(); } return l; } private: void help(vector<int> &r, TreeNode* t){ if(!t) return; help(r, t->left); if(!t->left && !t->right) { r.push_back(t->val); } help(r, t->right); } };
No comments :
Post a Comment