天天看点

[每日一道小算法(四十三)] [递归] 二叉搜索树的第k个节点(剑指offer)

前言:

剑指offer中树的题型,最后一道,下面我会刷字符串、数组相关的题。

题目描述

题目解析

代码样例

package com.asong.leetcode.TreeKthNode;

import java.util.ArrayList;

/**
 * 二叉搜索树的第K个节点
 */
public class Solution {
    public ArrayList<TreeNode> list = new ArrayList<TreeNode>();
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        Middle(pRoot);
        if(list.size()>=k&&k>=1)
        {
            return list.get(k-1);
        }
        return null;
    }
    public void Middle(TreeNode pRoot)
    {
        if(pRoot!=null)
        {
            Middle(pRoot.left);
            list.add(pRoot);
            Middle(pRoot.right);
        }
    }
}