Redian新闻
>
Find the node with given value in binary tree in in-order
avatar
Find the node with given value in binary tree in in-order# JobHunting - 待字闺中
h*p
1
Find the node with given value in binary tree in in-order way,and return it;
PS: the binary tree may include two nodes with the same value.
感觉老写不对
哪位大牛分享下solution?
谢谢
avatar
b*5
2
什么叫 in in-order way, 是不是就写个inorder walk, 然后顺便查查是不是equal?
avatar
T*e
3
本菜鸟的想法:
inorder遍历的时候如果目标是当前节点,检查左子树(如果有返回值返回)
如果目标不是当前节点,返回左子树(假如有值的话),否则返回右子树
avatar
i*s
4
不知道理解得是否正确,
如果存在多个值等于val,则返回in-order遍历最先找到的这个节点
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
bool find(TreeNode* root, TreeNode*& ret, int val) {
if (root == NULL) {
return false;
}
if (root->left != NULL && find(root->left, ret, val)) {
return true;
}
if (root->val == val) {
ret = root;
return true;
}
if (root->right != NULL && find(root->right, ret, val)) {
return true;
}
return false;
}
avatar
s*u
5
首先要确定下是不是BST,这里假定不是。
TreeNode *search(TreeNode *root, int key ){

if( root == NULL )
return NULL;

TreeNode *res = search(root->left,key);

if(res)
return res;

if(root->val == key )
return root;

res = search(root->right,key);
return res;
}
avatar
s*u
6
既然root已经处理了null的情况,个人觉得就不用去判断root->left或root->right是
否为NULL了。或者反之。

【在 i********s 的大作中提到】
: 不知道理解得是否正确,
: 如果存在多个值等于val,则返回in-order遍历最先找到的这个节点
: struct TreeNode {
: int val;
: TreeNode* left;
: TreeNode* right;
: };
: bool find(TreeNode* root, TreeNode*& ret, int val) {
: if (root == NULL) {
: return false;

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。