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

二叉搜索树的第k个节点

https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

public class Solution {
    public int KthNode(TreeNode proot, int k) {
         if (proot == null) return -1;
        if (k>=1) {
            for (int i = 1; i < k; i++) {
                int val = getMinNodeVal(proot);
                if (val==1001) return -1;
                excludeNodeByVal(proot, val);
            }
              if (getMinNodeVal(proot)==1001) return -1;
            return getMinNodeVal(proot);
        }
        return -1;
    }

    private TreeNode excludeNodeByVal(TreeNode node, int val) {
        if (node == null) return null;
        TreeNode res = node;

        if (node.val == val) {
            res.val = 1001;
            return res;
        }
        excludeNodeByVal(node.left, val);
        excludeNodeByVal(node.right, val);
        return res;
    }

    private int getMinNodeVal(TreeNode node) {
        if (node == null) {
            return 1001;
        }
        int minNode = Math.min(getMinNodeVal(node.left), getMinNodeVal(node.right));
        if (node.val < minNode) return node.val;
        return minNode;
    }
}

丑陋的代码

全部评论

相关推荐

10-27 17:26
东北大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务