向二叉搜索樹中插入節點

向二叉搜索樹插入節點需要保持其本身的性質,即節點左子樹的節點值皆小於其根節點的值,節點右子樹的節點值皆大於其根節點的值。

這裏使用遞歸解決

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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章