剑指offer:Python 二叉搜索树的第k个结点 二叉树的中序遍历

题目描述

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

思路及Python实现

  • 如下图的二叉搜索树,因为二叉搜索树如果中序遍历的话,它是有序的,那么第k小的结点,就是第k个结点,所以只需要中序遍历即可!
    在这里插入图片描述
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        ret = []

        def in_order(root):
            if root is None:
                return None
            in_order(root.left)
            ret.append(root)
            in_order(root.right)

        in_order(pRoot)
        if len(ret) < k or k < 1:
            return None
        else:
            return ret[k - 1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
用C++求二叉树中序遍历的结果并打印可以使用递归方法实现,具体步骤如下: 1. 如果当前结点为空,返回。 2. 递归遍历左子树。 3. 输出当前结点。 4. 递归遍历右子树。 中序遍历的最后一个结点即为二叉树的最右下角结点,可以在递归遍历时记录最后一个结点中序遍历的第n个结点可以在递归遍历时使用一个计数器来记录当前是第几个结点,并在遍历到第n个结点时输出。 以下是示例代码: ```c++ #include <iostream> using namespace std; // 二叉树结点定义 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void inorderTraversal(TreeNode* root) { if (root == NULL) { return; } inorderTraversal(root->left); cout << root->val << " "; inorderTraversal(root->right); } TreeNode* getInorderLastNode(TreeNode* root) { if (root == NULL) { return NULL; } while (root->right != NULL) { root = root->right; } return root; } int getInorderNthNode(TreeNode* root, int n, int& count) { if (root == NULL) { return -1; } int res = getInorderNthNode(root->left, n, count); if (count == n) { return root->val; } count++; if (res != -1) { return res; } return getInorderNthNode(root->right, n, count); } int main() { // 构建一个二叉树 TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); // 中序遍历 inorderTraversal(root); cout << endl; // 中序遍历的最后一个结点 TreeNode* lastNode = getInorderLastNode(root); cout << lastNode->val << endl; // 中序遍历的第n个结点 int n = 3; int count = 1; int nthNode = getInorderNthNode(root, n, count); cout << nthNode << endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值