【剑指offer】二叉查找树的第K个结点(python)

  1. 二叉搜索树的中序(左中右)遍历结果就是升序序列,因为其左节点都小于根节点,右结点都大于根节点。
  2. 注意边界值,0<k<=length
    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
     # 返回对应节点TreeNode
     arr = []
     def KthNode(self, pRoot, k):
         # write code here
         if not pRoot: 
             return None
         self.arr = []
         self.midTraversal(pRoot)
         length = len(self.arr)
         if k <= length and k > 0:
             return self.arr[k-1]
         else:
             return None
     def midTraversal(self,root):
         if not root: 
             return None
         self.midTraversal(root.left)
         self.arr.append(root)
         self.midTraversal(root.right)