leetcode405删除二叉搜索树中的节点

109 阅读1分钟

450 删除二叉搜索树中的节点

给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。 一般来说,删除节点可分为两个步骤: 首先找到需要删除的节点; 如果找到了,删除它。 说明: 要求算法时间复杂度为 O(h),h 为树的高度。
示例: root = [5,3,6,2,4,null,7] key = 3

5

   / \

  3   6

 / \   \

2   4   7
给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。 一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。

5

   / \

  4   6

 /     \

2       7
另一个正确答案是 [5,2,6,null,4,null,7]。

5

   / \

  2   6

   \   \

    4   7
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/de… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution(object):
    def findMin(self,root):
        if(root is None):
            return None
        if(root.left is None): 
            return root
        else:   
            return self.findMin(root.left)
    def deleteNode(self, root, key):
        if(root is None):
            return None
        if(key<root.val):
            root.left=self.deleteNode(root.left,key)
        elif(key>root.val):
            root.right=self.deleteNode(root.right,key)
        else:
            if(root.left is not None and root.right is not None):
                root.val=self.findMin(root.right).val
                print(root.val)
                root.right=self.deleteNode(root.right,root.val)
            elif(root.left is not None or root.right is not None):
                old=root
                root = root.left if root.left is not None else root.right
                del old
            elif(root.left is None and root.right is None):
                del root 
                return None
        return root