C++ straight-forward solution


  • 0
    M
        vector<int> boundaryOfBinaryTree(TreeNode* root) {
            if(root==NULL) return {};
            else if(root->left==NULL&&root->right==NULL) return {root->val};
            vector<int> res(1, root->val), temp;
            TreeNode* r=root->left;
            while(r!=NULL) {
                res.push_back(r->val);
                if(r->left) r=r->left;
                else r=r->right;
            }
            r=root->right;
            while(r!=NULL) {
                temp.push_back(r->val);
                if(r->right) r=r->right;
                else r=r->left;
            }
            if(res.size()>1) res.pop_back();
            if(temp.size()!=0) temp.pop_back();
            reverse(temp.begin(), temp.end());
            DFS(root, res);
            for(int i=0;i<temp.size();i++) res.push_back(temp[i]);
            return res;
        }
        
        void DFS(TreeNode* r, vector<int>& a) {
            if(r->left==NULL&&r->right==NULL)  {
                a.push_back(r->val);
                return;
            }
            if(r->left) DFS(r->left, a);
            if(r->right) DFS(r->right, a);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.