700. 二叉搜索树中的搜索

image.png

递归实现

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func searchBST(root *TreeNode, val int) *TreeNode {
  10. if root==nil{
  11. return nil
  12. }
  13. if root.Val==val{
  14. return root
  15. }else if root.Val>val{
  16. return searchBST(root.Left,val)
  17. }else {
  18. return searchBST(root.Right,val)
  19. }
  20. }

迭代实现

package main

import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func searchBST(root *TreeNode, val int) *TreeNode {
    stack := make([]*TreeNode,0)
    if root.Val==val{
        return root
    }else if root.Val>val&&root.Left!=nil{
        stack = append(stack,root.Left)
    }else if root.Val<val&&root.Right!=nil{
        stack = append(stack,root.Right)
    }
    for len(stack)>0{
        node :=stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if node.Val==val{
            return node
        }else if node.Val>val&&node.Left!=nil{
            stack = append(stack,node.Left)
        }else if node.Val<val&&node.Right!=nil{
            stack = append(stack,node.Right)
        }
    }
    return nil
}



func main() {
    four :=&TreeNode{Val:   4,}
    two :=&TreeNode{Val:   2,}
    seven :=&TreeNode{Val:   7,}
    one :=&TreeNode{Val:   1,}
    three :=&TreeNode{Val:   3,}
    four.Left = two
    four.Right = seven
    two.Left =one
    two.Right = three
    r :=searchBST1(four,7)
    if r!=nil{
        fmt.Println(r.Val)
    }
}

image.png