使用顺序遍历搜索二叉树中的元素

问题描述 投票:0回答:2
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;
}

我不知道上面的代码如何在搜索树时找不到0时返回val

c search data-structures binary-tree
2个回答
0
投票

你有什么非结构化的功能。有四个返回语句和五个可能的返回路径。其中一个返回显式返回零,其他返回显式返回1,因此要么为search调用root为NULL,要么第五个隐式返回路径恰好返回零。

拨打编译器的警告级别,它应该标记并非所有执行路径都返回值的事实。

我建议你重新安排你的逻辑,这样在函数的末尾有一个return语句。


-1
投票

在这里,我使用堆栈进行树的迭代顺序遍历。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.