二叉搜索树中的搜索
题目:
给定二叉搜索树(BST)的根节点和一个值。你需要在 BST 中找到节点值等于给定值的节点。返回以该节点为根的子树。如果节点不存在,则返回 NULL 。
示例:
给定二叉搜索树:
        4
       / \
      2   7
     / \
    1   3
    
和值: 2
返回如下子树:
      2     
     / \   
    1   3
递归方法:
func Getson1(root *Node, value int64) *Node {
	if root == nil {
		return nil
	}
	if root.Value > value {
		return Getson1(root.Left, value)
	} else if root.Value < value {
		return Getson1(root.Rigth, value)
	} else {
		return root
	}
	return nil
}
迭代方法:
func GetSon2(root *Node, value int64) *Node {
	for root != nil {
		if root.Value > value {
			root = root.Left
		} else if root.Value < value {
			root = root.Rigth
		} else {
			return root
		}
	}
	return nil
}
地址:https://mp.weixin.qq.com/s/iIm3M7HsPiKBNJo37jxIdg
    small_lei_it  技术无止境,追求更高。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号