【LeetCode每日一题】[中等]701. 二叉搜索树中的插入操作

【LeetCode每日一题】[中等]701. 二叉搜索树中的插入操作

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

题目来源
算法思想:搜索二叉树

题目:
在这里插入图片描述

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 * }
 */
//使用的插入方法是,将要插入的结点插入到叶子节点
class Solution {
    
    
    public TreeNode insertIntoBST(TreeNode root, int val) {
    
    
        if(root == null) {
    
    //如果二叉树为空,则插入到根节点
			return new TreeNode(val);
		}
		TreeNode temp = root;//指向root索引,用来遍历二叉树
		while (temp != null){
    
    
			if (temp.val > val) {
    
    //val比结点值小,则插入左子树,向左子树遍历
				if(temp.left == null) {
    
    //如果左节点为null,则将节点插入左节点
					temp.left = new TreeNode(val);
					break;
				}
				temp = temp.left;
			}
			else {
    
    //val比结点值大,则插入右子树,向右子树遍
				if(temp.right == null) {
    
    //如果右节点为null,则将节点插入右节点
					temp.right = new TreeNode(val);
					break;
				}
				temp = temp.right;
			}
		}
		return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/108883083
今日推荐