第62题——二叉搜索树的第k个节点

262 阅读1分钟

题目:

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

思路:

考虑二叉搜索树的特性,中序遍历这课树就是顺序的,那么加一个count,中序遍历这课树,也就是从树的左子树的最左端开始,没出一个值就count++,直到count=k

Java

package nowcoder;

import java.util.Stack;

public class S62_KthNode {
    int count = 0;
    public TreeNode KthNode(TreeNode pRoot, int k){
        if (pRoot == null || count > k)
            return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = pRoot;
        TreeNode result = null;
        while (!stack.isEmpty() || p != null){
            while (p != null){
                stack.add(p);
                p = p.left;
            }
            TreeNode node = stack.pop();
            count++;
            if (count == k)
                result = node;
            p = node.right;
        }
        return result;
    }
    public static void main(String[] args){
        S62_KthNode s62 = new S62_KthNode();
        Integer[] array = {5, 3, 7, 2, 4, 6, 8};
        PrintTreeLayer p = new PrintTreeLayer();
        TreeNode root = p.arrayToTree(array, 0);
        System.out.println(s62.KthNode(root, 3).val);
    }
}

Python

import PrintTreeLayer
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class KthNode:
    def kthNode(self, root, k):
        self.res = []
        self.dfs(root)
        return self.res[k-1] if 0 < k <= len(self.res) else None
    def dfs(self, root):
        if not root:
            return
        self.dfs(root.left)
        self.res.append(root)
        self.dfs(root.right)
if __name__ == '__main__':
    test = KthNode()
    array = [5, 3, 7, 2, 4, 6, 8]
    p = PrintTreeLayer.PrintTreeLayer()
    root = p.arrayToTree(array, 0)
    print(test.kthNode(root, 3).val)