[Leetcode][第98 450 700 701题][JAVA][二叉搜索树的合法性、增、删、查][递归][深度遍历]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第98 450 700 701题][JAVA][二叉搜索树的合法性、增、删、查][递归][深度遍历]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【二叉搜索樹定義】(BST)
二叉搜索樹(Binary Search Tree,簡稱 BST)是一種很常用的的二叉樹。它的定義是:一個二叉樹中,任意節點的值要大于等于左子樹所有節點的值,且要小于等于右邊子樹的所有節點的值。
【二叉樹算法框架】
void traverse(TreeNode root) {// root 需要做什么?在這做。// 其他的不用 root 操心,拋給框架traverse(root.left);traverse(root.right); }【二叉搜索樹算法框架】
void BST(TreeNode root, int target) {if (root.val == target)// 找到目標,做點什么if (root.val < target) BST(root.right, target);if (root.val > target)BST(root.left, target); }【問題描述】
實現 BST 的基礎操作:判斷 BST 的合法性、增、刪、查。
【解答思路】
1. 判斷 BST 的合法性
root 需要做的不只是和左右子節點比較,而是要整個左子樹和右子樹所有節點比較。
boolean isValidBST(TreeNode root) {return isValidBST(root, null, null); }boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {if (root == null) return true;if (min != null && root.val <= min.val) return false;if (max != null && root.val >= max.val) return false;return isValidBST(root.left, min, root) && isValidBST(root.right, root, max); }2. 在 BST 中查找一個數是否存在
框架
boolean isInBST(TreeNode root, int target) {if (root == null) return false;if (root.val == target) return true;return isInBST(root.left, target)|| isInBST(root.right, target); }利用特性
boolean isInBST(TreeNode root, int target) {if (root == null) return false;if (root.val == target)return true;if (root.val < target) return isInBST(root.right, target);if (root.val > target)return isInBST(root.left, target);// root 該做的事做完了,順帶把框架也完成了,妙 }3. 在 BST 中插入一個數
對數據結構的操作無非遍歷 + 訪問,遍歷就是“找”,訪問就是“改”。具體到這個問題,插入一個數,就是先找到插入位置,然后進行插入操作。
直接套BST 中的遍歷框架,加上“改”的操作即可。一旦涉及“改”,函數就要返回 TreeNode 類型,并且對遞歸調用的返回值進行接收。
4. 在 BST 中刪除一個數
TreeNode deleteNode(TreeNode root, int key) {if (root == null) return null;if (root.val == key) {// 這兩個 if 把情況 1 和 2 都正確處理了if (root.left == null) return root.right;if (root.right == null) return root.left;// 處理情況 3TreeNode minNode = getMin(root.right);root.val = minNode.val;root.right = deleteNode(root.right, minNode.val);} else if (root.val > key) {root.left = deleteNode(root.left, key);} else if (root.val < key) {root.right = deleteNode(root.right, key);}return root; }TreeNode getMin(TreeNode node) {// BST 最左邊的就是最小的while (node.left != null) node = node.left;return node; }注意一下,這個刪除操作并不完美,因為我們一般不會通過 root.val = minNode.val 修改節點內部的值來交換節點,而是通過一系列略微復雜的鏈表操作交換 root 和 minNode 兩個節點。因為具體應用中,val 域可能會很大,修改起來很耗時,而鏈表操作無非改一改指針,而不會去碰內部數據。
【總結】
1. 二叉樹算法設計的總路線:把當前節點要做的事做好,其他的交給遞歸框架,不用當前節點操心。
2.如果當前節點會對下面的子節點有整體影響,可以通過輔助函數增長參數列表,借助參數傳遞信息。
3.在二叉樹框架之上,擴展出一套 BST 遍歷框架
void BST(TreeNode root, int target) {if (root.val == target)// 找到目標,做點什么if (root.val < target) BST(root.right, target);if (root.val > target)BST(root.left, target); }轉載鏈接:https://leetcode-cn.com/problems/same-tree/solution/xie-shu-suan-fa-de-tao-lu-kuang-jia-by-wei-lai-bu-/
總結
以上是生活随笔為你收集整理的[Leetcode][第98 450 700 701题][JAVA][二叉搜索树的合法性、增、删、查][递归][深度遍历]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HoloLens开发手记 - Unity
- 下一篇: MOSSE到KCF