自创思路:
val与各个root.val比较,大了就往右走,小了就往左走;
到底了(root.left == None or root.right == None) 就new TreeNode(val),粘到其父节点上。
自创迭代法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
res = root
if not root:
return TreeNode(val)
while root:
if val > root.val:
if not root.right:
root.right = TreeNode(val)
return res
else:
root = root.right
elif val < root.val:
if not root.left:
root.left = TreeNode(val)
return res
else:
root = root.left
递归思路:
递归结束条件:遇到None就new TreeNode(val)。将它返回给父节点的孩子(在上一层递归中)
递归单层逻辑:val与各个root.val比较,大了就往右走,小了就往左走。所以每次只会选择一条路走(要么左,要么右)。
注意:注意理解每一层孩子节点是如何返回给其父节点的。(in other words, 父节点是如何指向其孩子节点的)
递归法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
#要么右拐,走这条路
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
#要么左拐,走这条路
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
return root
Carl迭代法:
思路:
用parent变量指向前一节点。
先用while循环找到待插入的叶子节点(最底层父节点root。在代码中时parent);
根据父节点root.val(parent.val) 与 val的值大小关系,决定插在root的左孩子还是右孩子;
迭代法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
parent = None
cur = root
while cur:
parent = cur
if val > cur.val:
cur = cur.right
elif val < cur.val:
cur = cur.left
#此处意味着已找到parent,最底层的父节点
if val < parent.val:
parent.left = TreeNode(val)
else:
parent.right = TreeNode(val)
return root
总结:
首先在二叉搜索树中的插入操作,大家不用恐惧其重构搜索树,其实根本不用重构。
然后在递归中,我们重点讲了如何通过递归函数的返回值完成新加入节点和其父节点的赋值操作,并强调了搜索树的有序性。
最后依然给出了迭代的方法,迭代的方法就需要记录当前遍历节点的父节点了,这个和没有返回值的递归函数实现的代码逻辑是一样的。
References
leetcode-master/0701.二叉搜索树中的插入操作.md at master · youngyangyang04/leetcode-master · GitHub