本文主要是介绍java数据结构与算法刷题-----LeetCode669. 修剪二叉搜索树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846
二叉搜索树,当前结点左边都比它小,右边都比它大 所以我们前序遍历 如果当前结点node,比low小,说明它和左子树都小于low,抛弃,那么剩下右子树保留,使用同样的套路判断,因为右子树都比node大,无法确定是否抛弃 如果node比high大,抛弃右子树,左子树保留进行判断。
1. 递归
class Solution { public TreeNode trimBST ( TreeNode root, int low, int high) { if ( root == null ) return null ; int val = root. val; if ( val < low) return trimBST ( root. right, low, high) ; else if ( root. val > high) return trimBST ( root. left, low, high) ; else { root. left = trimBST ( root. left, low, high) ; root. right = trimBST ( root. right, low, high) ; return root; } }
}
2. 迭代
class Solution { public TreeNode trimBST ( TreeNode root, int low, int high) { while ( root != null && ( root. val < low || root. val > high) ) { if ( root. val < low) { root = root. right; } else { root = root. left; } } if ( root == null ) { return null ; } for ( TreeNode node = root; node. left != null ; ) { if ( node. left. val < low) { node. left = node. left. right; } else { node = node. left; } } for ( TreeNode node = root; node. right != null ; ) { if ( node. right. val > high) { node. right = node. right. left; } else { node = node. right; } } return root; }
}
这篇关于java数据结构与算法刷题-----LeetCode669. 修剪二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!