二叉搜索树的第k个结点
2019獨角獸企業重金招聘Python工程師標準>>>
題目描述
給定一顆二叉搜索樹,請找出其中的第k大的結點。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按結點數值大小順序第三個結點的值為4。
【解決】
① 使用一個變量記錄遍歷的個數
class TreeNode {
? ? int val = 0;
? ? TreeNode left = null;
? ? TreeNode right = null;
? ? public TreeNode(int val) {
? ? ? ? this.val = val;
? ? }
}
public class Solution {
? ? int count = 0;
? ? TreeNode KthNode(TreeNode pRoot, int k) {
? ? ? ? if (pRoot == null || k <= 0){
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? TreeNode res = null;
? ? ? ? if (pRoot.left != null){
? ? ? ? ? ? res = KthNode(pRoot.left,k);
? ? ? ? }
? ? ? ? count ++;
? ? ? ? if (res == null){
? ? ? ? ? ? if (count == k){
? ? ? ? ? ? ? ? res = pRoot;
? ? ? ? ? ? ? ? return res;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? if (res == null && pRoot.right != null){
? ? ? ? ? ? res = KthNode(pRoot.right,k);
? ? ? ? }
? ? ? ? return res;
? ? }
}
② 使用一個變量保存中序遍歷的結果
import java.util.ArrayList;
import java.util.List;
class TreeNode {
? ? int val = 0;
? ? TreeNode left = null;
? ? TreeNode right = null;
? ? public TreeNode(int val) {
? ? ? ? this.val = val;
? ? }
}
public class Solution {
? ? List<TreeNode> list = new ArrayList<>();
? ? TreeNode KthNode(TreeNode pRoot, int k) {
? ? ? ? if (k == 0) return null;
? ? ? ? inorder(pRoot);
? ? ? ? if (k > list.size()) return null;
? ? ? ? return list.get(k - 1);
? ? }
? ? public void inorder(TreeNode root){
? ? ? ? if (root == null) return;
? ? ? ? inorder(root.left);
? ? ? ? list.add(root);
? ? ? ? inorder(root.right);
? ? }
}
轉載于:https://my.oschina.net/liyurong/blog/1678807
總結
以上是生活随笔為你收集整理的二叉搜索树的第k个结点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 长连接 mysql数据库
- 下一篇: 从云计算到大数据华胜天成的国际化之路