LeetCode-二叉搜索树的第k大节点

二叉搜索树的第k大节点

LeetCode-面试题54

  • 需要充分了解二叉搜索树的性质.
  • 利用中序遍历的思想,采用相反的思想:先遍历右节点再遍历左节点。
/**
 * 给定一棵二叉搜索树,请找出其中第k大的节点。
 **/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
输入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
输出: 4
**/
class Solution {
private:
    int n=0;
    int result=0;
public:
    void DFS(TreeNode* node,int k){
        if(node->right)
            DFS(node->right,k);
        n++;
        if(n==k)
            result=node->val;
        if(node->left)
            DFS(node->left,k);
    }
    int kthLargest(TreeNode* root, int k) {
        if(root)
            DFS(root,0);
        return result;
    }
};
int main(){
    TreeNode* t1=new TreeNode(5);
    TreeNode* t2=new TreeNode(3);
    TreeNode* t3=new TreeNode(6);
    TreeNode* t4=new TreeNode(2);
    TreeNode* t5=new TreeNode(4);
    TreeNode* t6=new TreeNode(1);
    t4->left=t6;
    t2->left=t4;t2->right=t5;
    t1->left=t2;t1->right=t3;
    Solution solution;
    cout<<solution.kthLargest(t1,3)<<endl;
    system("pause");
    return 0;
}
posted @ 2020-02-24 20:26  Garrett_Wale  阅读(327)  评论(0编辑  收藏  举报