皮皮的LeetCode刷题库二叉树之下

【剑指Offer】062——二叉树的第k个结点 (栈、树)

2019-08-23  本文已影响14人  就问皮不皮

62.二叉树的第k个结点 (栈、树)

题目描述

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

解题思路

因为二叉搜索树按照中序遍历的顺序打印出来就是排好序的,所以,我们按照中序遍历找到第k个结点就是题目所求的结点。本程序在设计中,当遍历到k时就一直返回当前这个查询到的结点,其他情况返回空,程序中存在不返回空的语句,这个是在查找到之后向前返回查找到的那个结点用的。

参考代码

Java

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    int index = 0; // 全局变量,与k比较
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        // 中序遍历到第k个为止
        if(pRoot != null){
            // 前
            TreeNode node = KthNode(pRoot.left, k);
            if(node != null)
                return node;
            // 根
            index ++;
            if(index == k)
                return pRoot;
            // 后
            node = KthNode(pRoot.right, k);
            if(node != null)
                return node;
        }
        return null;
    }
}

Python

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回对应节点TreeNode
    def __init__(self):
        self.index = 0
    def KthNode(self, pRoot, k):
        # write code here
        if pRoot:
            node = self.KthNode(pRoot.left,k)
            if node:return node
            self.index += 1
            if self.index == k: return pRoot
            node = self.KthNode(pRoot.right,k)
            if node:
                return node
        return None

个人订阅号

image
上一篇 下一篇

猜你喜欢

热点阅读