我需要帮助使用int数据(不一定是二叉搜索树)搜索二叉树,并查看元素是否在树中。如果它在树中返回引用,如果未找到则返回null。这是我到目前为止的代码。
Node search(TreeNode root, int key){
if(root == null){
return null;
}
search(root.left, key);
search(root.right, key);
if(root.right.data === key || root.left.data == key){
return root;
}else{
return null;
}
}
答案 0 :(得分:1)
您致电search(root.left, key);
。那样太好了。除非您正在搜索的元素确实位于当前节点的左侧分支中,否则不会发生任何事情。无论递归调用报告什么,该方法都会继续执行。您需要保留该数据并进行适当处理。
因此你应该这样做:
Node search(TreeNode root, int key){
if (root == null)
return null;
if (root.data == key)
return root;
Node n;
n = search(root.left, key);
if (n != null)
return n;
n = search(root.right, key);
if (n != null)
return n;
return null;
}