Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
2
Indexable
Never
void left(TreeNode<int> *root, vector<int> &ans){
    if(root==NULL || (root->left==NULL &&root->right==NULL)) return;  //check null,leaf
    ans.push_back(root->data);  //add left value to ans
    if(root->left) {                //traverse to left or to right child if left absent
        left(root->left,ans);  
    }else{
        left(root->right,ans);
    }
}

void leafT(TreeNode<int> *root, vector<int> &ans){  //LNR
    if(root==NULL) return ; //we have to traverse
    if(root->left==NULL && root->right ==NULL){
        ans.push_back(root->data);
        return;   //now we can return as it leaf no furthe rcheck
    }
    if(root->left) leafT(root->left,ans);
    if(root->right) leafT(root->right,ans);

}

void right(TreeNode<int> *root, vector<int> &ans){
    if(root==NULL || (root->left==NULL &&root->right==NULL)) return;
    
    if(root->right) {
        right(root->right,ans);
    }else{
        right(root->left,ans);
    }
    ans.push_back(root->data);
    
}


vector<int> traverseBoundary(TreeNode<int> *root)
{
	vector<int> ans;
    if(root==NULL) return ans;
    ans.push_back(root->data);
    left(root->left, ans);
    leafT(root,ans);
    right(root->right,ans);
    return ans;
}