#数据结构与算法学习笔记#剑指Offer60:二叉搜索树的第K个结点(Java、C/C++)

版权声明:本文为博主NJU_ChopinXBP原创文章,发表于CSDN,仅供交流学习使用,转载请私信或评论联系,未经博主允许不得转载。感谢您的评论与点赞。 https://blog.csdn.net/qq_20304723/article/details/88050702

2019.3.1     《剑指Offer》从零单刷个人笔记整理(66题全)目录传送门​​​​​​​

这题可以简单在纸上画一下,可以发现二叉搜索树的元素排序顺序,就是其中序遍历顺序。那就很简单了,中序遍历走一遍走到第K个结点返回即可。


题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。


Java实现:

/**
 * 
 * @author ChopinXBP
 * 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
 * 
 */



public class KthNode_61 {
	
	public static class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;

	    public TreeNode(int val) {
	        this.val = val;
	    }
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	private static int num;
	private static TreeNode result;
	
	public static TreeNode KthNode(TreeNode pRoot, int k)
    {
        num = 0;
        result = null;
        Solution(pRoot, k);
        
        return result;
    }
	
	public static void Solution(TreeNode pRoot, int k) {
		if(pRoot == null || num == k) {
			return;
		}
		Solution(pRoot.left, k);
		num++;
		if(num == k) {
			result = pRoot;
			return;
		}
		Solution(pRoot.right, k);
	}
}

C++实现示例:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    void inorder(TreeNode* root,TreeNode* &ans){
        if(root){
            inorder(root->left,ans);
            count--;
            if(!count) ans = root;
            inorder(root->right,ans);
        }
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot || k < 1) return nullptr;
        TreeNode* ans = NULL;
        count = k;
        inorder(pRoot,ans);
        return ans;
    }
private:
    int count;
     
};

#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/88050702