简体   繁体   中英

searching an element in binary tree using in order traversal

struct tnode
{
    int val;
    struct tnode *left;
    struct tnode *right;
};

int search(struct tnode *root, int val)
{
    int p = 0;
    int q = 0;
    if (!root) return 0;
    p = search(root->left, val);
    if (p == 1) return 1;
    if (root->val == val) return 1;
    q = search(root->right, val);
    if (q == 1) return 1;
}

I am not understanding how the above code is returning 0 when val is not found while searching the tree.

What you have there is an unstructured function. There are four return statements and five possible return paths. One of the returns explicitly returns zero, the others explicitly return 1, therefore either you are calling search with NULL for root or the fifth implicit return path just happens to return zero.

Dial up the warning level on your compiler, it should have flagged the fact that not all execution paths return a value.

I suggest you rearrange your logic such that there is a single return statement at the end of the function.

Here, I am using stack for the iterative inorder traversal of a tree.

int find_element(struct node *root,int val){

     if(!root) return 0;
     std::stack<node*> s;
     while(!s.empty() || root){
          if(root){
              s.push(root);
              root=root->left;
          }
          else
          {
              root=s.top();
              s.pop();
              if(root->val==val) return 1;
              root=root->right;
          }
     }
     return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM