其他分享
首页 > 其他分享> > 剑指offer 54、二叉搜索树的第k大节点

剑指offer 54、二叉搜索树的第k大节点

作者:互联网

方法1:中序反向遍历,找到后还会继续遍历

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
        int result = 0;
        dfs(root, result, k);
        return result;
    }

private:
    void dfs(TreeNode *root, int &result, int &k) {
        if (!root) return;
        dfs(root->right, result, k);
        if (!--k) result = root->val;
        dfs(root->left, result, k);
    }
};

方法2:遍历到后就停止

class Solution {
public:
    int kthLargest(TreeNode* root, int &k) {
        if (!root) return 0;
        int result = kthLargest(root->right, k);
        if (!--k) return root->val;
        return k < 0 ? result : kthLargest(root->left, k);
    }
};

方法3:非递归方式

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
        vector<TreeNode*> worker;
        while (root || worker.size()) {
            while (root) {
                worker.push_back(root); // 根入栈
                root = root->right; // 访问右子树,向下探
            }
            root = worker.back(), worker.pop_back(); // 出栈
            if (!--k) return root->val;
            root = root->left; // 访问左子树
        }
        return 0;
    }
};

 

 

 

 

标签:return,offer,int,54,kthLargest,worker,二叉,result,root
来源: https://blog.csdn.net/m0_38062470/article/details/114819187