首页 > 其他 > 详细

450. 删除二叉搜索树中的节点

时间:2020-07-13 09:57:42      阅读:44      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) { 
        if(root == null) return null;
        if(root.val == key) {
            if(root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {  // 左右子树都不为null,将左子树连到,右子树的最左节点,返回右子树根节点
             // 也可将右子树连到,左子树的最右节点,返回左子树的根节点
TreeNode node = root.right; while(node.left != null) { node = node.left; } node.left = root.left; return root.right; } } if(root.val > key) { root.left = deleteNode(root.left,key); // 递归去左子树删除节点 } else { root.right = deleteNode(root.right,key); // 递归去右子树删除节点 } return root; // 返回删除操作之后子树的根节点 } }

 

450. 删除二叉搜索树中的节点

原文:https://www.cnblogs.com/yonezu/p/13291670.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!