[程式設計題] lc [劍指 Offer 54二叉搜尋樹的第k大節點----或者是求第K小元素]
阿新 • • 發佈:2020-07-26
[程式設計題] lc:劍指 Offer 54. 二叉搜尋樹的第k大節點
[程式設計題] JZ:劍指 Offer 62. 二叉搜尋樹的第k小節點
<1>題目1 描述:
輸入輸出
思路
根據二叉搜尋樹的特點:
- 根據二叉搜尋樹的特點,中序遍歷是從小到大排序,求第k小恰好是第k個節點,我們按照左 根 右 搜尋。(搜尋過程中判斷k值是否達到,退出!)
- 中序遍歷是從小到大排序,那麼求k大恰好是二叉搜尋樹的倒序的第K個; 即按照右 根 左的方式訪問遍歷(搜搜過的過程中不斷驗證K值是否達到退出)
Java程式碼(求二叉排序樹中的第K小)
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { /*思路:根據二叉搜尋樹的特點,中序遍歷是從小到大排序,求第k小恰好是第k個節點,我們按照左 根 右 搜素 那麼求k大恰好是二叉搜尋樹的倒序的第K個,即按照右 根 左的方式訪問遍歷(力扣) */ int k; TreeNode node; TreeNode KthNode(TreeNode pRoot, int k){ this.k = k; dfs(pRoot); return node; } public void dfs(TreeNode root){ //遞迴的退出條件 if(root==null){return;} //左遞迴 dfs(root.left); //判斷返回第k大個元素 k--; if(k==0){node = root;} //右遞迴 dfs(root.right); } }
Java程式碼(求二叉排序樹中的第K大)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { /*思路:根據二叉搜尋樹的特點,中序遍歷是從小到大排序,那麼求k大恰好是二叉搜尋樹的倒序的第K個; 即按照右 根 左的方式訪問遍歷 */ int k; int res; public int kthLargest(TreeNode root, int k) { this.k=k; dfs(root); return res; } public void dfs(TreeNode root){ if(root==null){return;} //右遞迴 dfs(root.right); k--; if(k==0){ res = root.val;} dfs(root.left); } }