設計一個算法,找出二叉搜索樹中指定節點的“下一個”節點(也即中序後繼)。
如果指定節點沒有對應的“下一個”節點,則返回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
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/successor-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
if root == nil {
return nil
}
flag := 0
res := &TreeNode{0,nil,nil}
run(root,p,res,&flag)
//2表示找到了後繼節點
if flag != 2 {
return nil
}
return res
}
func run(root,p,res *TreeNode,flag *int) {
if root == nil || *flag == 2 {
return
}
run(root.Left,p,res,flag)
if *flag == 1 {
*res = *root
//已經找到了後繼節點
*flag = 2
return
}
if root.Val == p.Val {
//表示下一個節點爲後繼節點
*flag = 1
}
run(root.Right,p,res,flag)
}