Java 按顺序在二叉树中找到给定值的节点并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19326991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:08:37 来源:igfitidea点击:
Find the node with given value in binary tree in in-order way and return it
提问by Nathan
find the node in binary tree in inorder way, and return it PS: the binary tree may include two nodes with the same value. it's easy to do it in pre-order way
中序查找二叉树中的节点,并返回 PS:二叉树可能包含两个值相同的节点。以预购方式很容易做到
Node find(Node root, int val){...}
anyone can share a solution?
任何人都可以分享解决方案吗?
采纳答案by smk
Havent tested it out thoroughly but this code should work.
尚未对其进行彻底测试,但此代码应该可以工作。
public TreeNode find(TreeNode cur,int val) {
TreeNode result = null;
if(cur.left != null)
result = find(cur.left,val);
if(cur.value == val)
return cur;
if(result ==null && cur.right != null)
result = find(cur.right,val);
return result;
}