Prove safety Offer - k-th largest node 54. The face questions binary search tree (binary tree traversal cycle)

1. Topic

Given a binary search tree, please find out the k-th largest nodes.

示例 1:
输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 4

示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
输出: 4
 
限制:
1 ≤ k ≤ 二叉搜索树元素个数

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

Please refer to: binary tree traversal cycle written summary

2.1 circulating solution

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
        //右根左降序遍历
        stack<TreeNode*> s;
        while(root || !s.empty())
        {
        	while(root)
        	{
        		s.push(root);
        		root = root->right;
        	}
        	root = s.top();
        	s.pop();
        	k--;
        	if(k==0)
        		return root->val;
        	root = root->left;
        }
        return -1;
    }
};

Here Insert Picture Description

2.2 recursive solution

class Solution {
	bool found = false;
	int ans;
public:
    int kthLargest(TreeNode* root, int k) {
        dfs(root,k);
        return ans;
    }

    void dfs(TreeNode* root, int& k)
    {
    	if(!root || found)
        	return;
        dfs(root->right,k);
        k--;
        if(k == 0)
        {
        	found = true;
        	ans = root->val;
        }
        dfs(root->left,k);
    }
};

Here Insert Picture Description

Published 644 original articles · won praise 496 · Views 140,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104332968