题目
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:输入: root = [2,1,3], p = 1
2
/
1 3
输出: 2
示例 2:输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/
3 6
/
2 4
/
1
输出: null
解题思路分析
1、递归;时间复杂度O(n),空间复杂度O(n)
![93109b0e9cdc81d0f93cb212b28b7846.png](https://i-blog.csdnimg.cn/blog_migrate/7bb4c99e8b432192a1b8c6a41d199281.jpeg)
var res []*TreeNodefunc inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {res = make([]*TreeNode, 0)dfs(root)for i := 0; i < len(res)-1; i++ {if res[i] == p {return res[i+1]}}return nil}func dfs(root *TreeNode) {if root == nil {return}dfs(root.Left)res = append(res, root)dfs(root.Right)}
2、递归;时间复杂度O(log(n)),空间复杂度O(log(n))
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {if root == nil {return nil}if p.Val >= root.Val {return inorderSuccessor(root.Right, p)}res := inorderSuccessor(root.Left, p)if res == nil {return root}return res}
3、迭代;时间复杂度O(log(n)),空间复杂度O(1)
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {var res *TreeNodecur := rootfor cur != nil {if p.Val >= cur.Val {cur = cur.Right} else {res = curcur = cur.Left}}return res}
总结
Medium题目,考察树的知识点,可以先递归保存节点再遍历,也可以利用二叉搜索树的特性进行遍历