向二叉搜索樹插入節點需要保持其本身的性質,即節點左子樹的節點值皆小於其根節點的值,節點右子樹的節點值皆大於其根節點的值。
這裏使用遞歸解決
class Solution{
public TreeNode insert(TreeNode root, TreeNode node){
if(root == null){
return node;
} // 此時遍歷到空引用,返回節點node引用即可
if(node.val < root.val){
root.left = insert(root.left, node);
}else{
root.right = insert(root.right, node);
}
return root;
}
}