From c76ed37fc487bc7da34403bbb484e9e42b582efb Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 2 May 2023 23:55:58 -0400 Subject: [PATCH] adding java iteration method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 迭代方法 --- ...11\346\220\234\347\264\242\346\240\221.md" | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git "a/problems/0669.\344\277\256\345\211\252\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" "b/problems/0669.\344\277\256\345\211\252\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" index 18d8a0cc8d..5739f7622d 100644 --- "a/problems/0669.\344\277\256\345\211\252\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" +++ "b/problems/0669.\344\277\256\345\211\252\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" @@ -248,6 +248,8 @@ public: ## Java +**递归** + ```Java class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { @@ -269,6 +271,46 @@ class Solution { ``` +**迭代** + +```Java +class Solution { + //iteration + public TreeNode trimBST(TreeNode root, int low, int high) { + if(root == null) + return null; + while(root != null && (root.val < low || root.val > high)){ + if(root.val < low) + root = root.right; + else + root = root.left; + } + + TreeNode curr = root; + + //deal with root's left sub-tree, and deal with the value smaller than low. + while(curr != null){ + while(curr.left != null && curr.left.val < low){ + curr.left = curr.left.right; + } + curr = curr.left; + } + //go back to root; + curr = root; + + //deal with root's righg sub-tree, and deal with the value bigger than high. + while(curr != null){ + while(curr.right != null && curr.right.val > high){ + curr.right = curr.right.left; + } + curr = curr.right; + } + return root; + } +} + +```` + ## Python **递归**