剑指offer54 二叉搜索树中第k小的节点

这个比较简单,考察的是对二叉搜索树的了解程度。

不了解通过举例子探索也可以发现,其实就是找其中序遍历中第k个数。

import java.util.ArrayList;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null||k<1) return null;
        
        ArrayList<TreeNode> ans = new ArrayList<>();
        int[] nodeCounts = new int[]{0};
        getInOrderTraverseSequence(pRoot,ans,nodeCounts);
        if(k>nodeCounts[0]) return null;
        return ans.get(k-1);
    }
    private void getInOrderTraverseSequence(TreeNode pRoot,ArrayList<TreeNode> ans,int[] nodeCounts){
        if(pRoot.left!=null) getInOrderTraverseSequence(pRoot.left,ans,nodeCounts);
        ans.add(pRoot);
        nodeCounts[0]++;
        if(pRoot.right!=null) getInOrderTraverseSequence(pRoot.right,ans,nodeCounts);
    }
}

运行时间:23ms

占用内存:9568k

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        if pRoot is None:
            return None
        inorder_arr = []
        node_count = [0]
        self.inOrderTraversal(pRoot,inorder_arr,node_count)
        if k>node_count[0] or k<1:
            return None
        else:
            return inorder_arr[k-1]
        
    def inOrderTraversal(self,root,arr,count):
        if root is None:
            return
        self.inOrderTraversal(root.left,arr,count)
        arr.append(root)
        count[0]+=1
        self.inOrderTraversal(root.right,arr,count)

运行时间:28ms

占用内存:5708k

posted @ 2019-03-03 21:36  大胖子球花  阅读(77)  评论(0)    收藏  举报