diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 7d71b517..8d448739 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -343,8 +343,32 @@ public: ## 其他语言版本 -### Java +### Java: +未剪枝优化 +```java +class Solution { + List> result= new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> combine(int n, int k) { + backtracking(n,k,1); + return result; + } + + public void backtracking(int n,int k,int startIndex){ + if (path.size() == k){ + result.add(new ArrayList<>(path)); + return; + } + for (int i =startIndex;i<=n;i++){ + path.add(i); + backtracking(n,k,i+1); + path.removeLast(); + } + } +} +``` +剪枝优化: ```java class Solution { List> result = new ArrayList<>(); diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 13599fd8..18e5cb4c 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -268,6 +268,34 @@ public: ### Java +```java +// 解法1(最好理解的版本) +class Solution { + public TreeNode deleteNode(TreeNode root, int key) { + if (root == null) return root; + if (root.val == key) { + if (root.left == null) { + return root.right; + } else if (root.right == null) { + return root.left; + } else { + TreeNode cur = root.right; + while (cur.left != null) { + cur = cur.left; + } + cur.left = root.left; + root = root.right; + return root; + } + } + if (root.val > key) root.left = deleteNode(root.left, key); + if (root.val < key) root.right = deleteNode(root.right, key); + return root; + } +} +``` + + ```java class Solution { public TreeNode deleteNode(TreeNode root, int key) { @@ -296,34 +324,59 @@ class Solution { } } ``` +递归法 ```java -// 解法2 class Solution { public TreeNode deleteNode(TreeNode root, int key) { - if (root == null) return root; - if (root.val == key) { - if (root.left == null) { - return root.right; - } else if (root.right == null) { - return root.left; - } else { - TreeNode cur = root.right; - while (cur.left != null) { - cur = cur.left; - } - cur.left = root.left; - root = root.right; - return root; + if (root == null){ + return null; + } + //寻找对应的对应的前面的节点,以及他的前一个节点 + TreeNode cur = root; + TreeNode pre = null; + while (cur != null){ + if (cur.val < key){ + pre = cur; + cur = cur.right; + } else if (cur.val > key) { + pre = cur; + cur = cur.left; + }else { + break; } } - if (root.val > key) root.left = deleteNode(root.left, key); - if (root.val < key) root.right = deleteNode(root.right, key); + if (pre == null){ + return deleteOneNode(cur); + } + if (pre.left !=null && pre.left.val == key){ + pre.left = deleteOneNode(cur); + } + if (pre.right !=null && pre.right.val == key){ + pre.right = deleteOneNode(cur); + } return root; } + + public TreeNode deleteOneNode(TreeNode node){ + if (node == null){ + return null; + } + if (node.right == null){ + return node.left; + } + TreeNode cur = node.right; + while (cur.left !=null){ + cur = cur.left; + } + cur.left = node.left; + return node.right; + } } ``` + ### Python + 递归法(版本一) ```python class Solution: