题解 | #二叉搜索树的第k个结点#

二叉搜索树的第k个结点

http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a

1.python 解法,使用栈来统计了,非递归模式:

# -*- 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
        #print('123')
        if not pRoot or not k:
            return None
        stack = []
        cur = pRoot
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                k -= 1
                cur = stack.pop()
                if k == 0:
                    return cur
                cur = cur.right
        return None

2.java解法,和python一样的思路:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot == null || k == 0){
            return null;
        }
        Stack<TreeNode> st = new Stack<>();
        TreeNode cur = pRoot;
        while(cur!=null || !st.isEmpty()){
            if(cur!=null){
                st.push(cur);
                cur = cur.left;
            }
            else{
                cur = st.pop();
                if(--k == 0){
                    return cur;
                }
                cur = cur.right;
            }
        }
        return null;
    }


}
  1. go解法不罗列了,go构建stack都烦的一比
全部评论

相关推荐

AaronRuan:看到了好多开奖了,不知道为啥自己也有点激动,真的替你们感到高兴啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务