Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2022-06-02]450. 删除二叉搜索树中的节点👋树👋二叉搜索树👋二叉树 #42

Open
webVueBlog opened this issue Jun 2, 2022 · 1 comment

Comments

@webVueBlog
Copy link
Member

题目链接: https://leetcode-cn.com/problems/delete-node-in-a-bst

难度: Medium
标签: 二叉搜索树 二叉树

@webVueBlog
Copy link
Member Author

/*
 * @lc app=leetcode.cn id=450 lang=javascript
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 (92 ms)
 */
 var deleteNode = function(root, key) {
    
  function callDFS(node) {
      if(!node) return null;
      if(node.val === key) {
          if(!node.left) return node.right;
          if(!node.right) return node.left;
          let curr = node.right;
          while(curr.left) curr = curr.left;
          curr.left = node.left;
          return node.right;
      }
      if(key > node.val) node.right = callDFS(node.right);
      else node.left = callDFS(node.left);
      return node;
  }
  return callDFS(root)
};
// @lc code=end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant