701. 二叉搜索树中的插入操作

138 阅读1分钟

力扣(LeetCode) 链接:leetcode-cn.com/problems/in…

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。

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

例如, 

给定二叉搜索树:

        4
       / \
      2   7
     / \
    1   3

和 插入的值: 5

你可以返回这个二叉搜索树:

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

思路

二叉树节点的性质: 任意节点的值,比其左子树所有节点的值都大,比其右子树所有节点的值都小。

题解:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
        	root = new TreeNode(val, null, null);
        	return root;
        }
        
        TreeNode node = root;
        TreeNode parent = root;
        int cmp = 0;
		while (node != null) {
			parent = node;
			//compare
			if (val > node.val) {
				node = node.right;
				cmp = 1;
			} else if (val < node.val) {
				node = node.left;
				cmp = -1;
			} else {
				// 相等则直接返回
				cmp = 0;
				break;
			}
		}
		
		TreeNode newNode = new TreeNode(val, null, null);
        if (cmp > 0) {
        	parent.right = newNode;
        } else if (cmp < 0){
        	parent.left = newNode;
        }
        return root;
    }
}