劍指offer-二叉搜索樹的第k個結點(python和c++)

題目描述

給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4。

思路:
二叉搜索樹按照中序遍歷的順序打印出來正好就是排序好的順序。
所以,按照中序遍歷順序找到第k個結點就是結果。

python

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回對應節點TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        #第三個節點是4
        #前序遍歷5324768
        #中序遍歷2345678
        #後序遍歷2436875
        #所以是中序遍歷,左根右
        global result
        result=[]
        self.midnode(pRoot)
        if  k<=0 or len(result)<k:
            return None
        else:
            return result[k-1]
              
    def midnode(self,root):
        if not root:
            return None
        self.midnode(root.left)
        result.append(root)
        self.midnode(root.right)

c++

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* KthNodeCore(TreeNode* pRoot, int& k) 
    { 
        TreeNode* target = NULL; 
 
        if(pRoot->left != NULL) 
            target = KthNodeCore(pRoot->left, k); 
 
        if(target == NULL) 
        { 
            if(k == 1) 
                target = pRoot; 
 
            k--; 
        } 
 
        if(target == NULL && pRoot->right != NULL) 
            target = KthNodeCore(pRoot->right, k); 
 
        return target; 
    } 
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
         if(pRoot == NULL || k == 0) 
        return NULL; 
           
        return KthNodeCore(pRoot, k); 
    }
 
     
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章