• [leetCode]701. 二叉搜索树中的插入操作


    题目

    题目:链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree

    给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

    注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。

    在这里插入图片描述

    递归

    class Solution {
        public TreeNode insertIntoBST(TreeNode root, int val) {
            if (root == null) { // 遍历的节点为null是说明到达了插入节点
                return new TreeNode(val);
            }
            if (root.val > val) root.left = insertIntoBST(root.left, val);
            if (root.val < val) root.right = insertIntoBST(root.right, val);
            return root;
        }
    }
    

    迭代

    class Solution {
        public TreeNode insertIntoBST(TreeNode root, int val) {
            if (root == null) {
                return new TreeNode(val);
            }
            TreeNode cur = root;
            TreeNode parent = null;
            while (cur != null) {
                parent = cur; // 在移动之前记录父节点
                if (cur.val > val) cur = cur.left;
                else if (cur.val <= val) cur = cur.right;
            }
            if (parent.val > val) {
                parent.left = new TreeNode(val);
            } else {
                parent.right = new TreeNode(val);
            }
            return root;
        }
    }
    
  • 相关阅读:
    职业生涯系列
    自我进修系列
    每周问题系列
    职业生涯系列
    软件测试专用名词
    Java系列 – 用Java8新特性进行Java开发太爽了(续)
    Java系列
    EJB系列
    EJB系列
    EJB系列
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13926578.html
Copyright © 2020-2023  润新知