ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 使用包装类而不是静态变量

2019-05-19 21:47:54  阅读:245  来源: 互联网

标签:java static binary-tree wrapper binary-search-tree


这是我在StackOverFlow上的第一个问题:
我正在学习采访“Cracking the code interview”(第5版)的书,
我正在解决下一个问题:

Implement a function to check if a binary tree is a binary search tree (Q 4.5 pg 86).

在继续之前,我想提醒您二进制搜索树与简单二叉树之间的区别:

A Binary search tree imposes the condition that for all nodes, the left children are less than or equal to the current node, which is less than all the right nodes.

因此,本书提供的解决方案之一是使用按顺序遍历扫描树,并在运行中检查我们访问的每个节点是否大于最后一个节点,并假设树不能具有重复值:

public static int last_printed = Integer.MIN_VALUE;
public static boolean checkBST(TreeNode n) {
    if(n == null) return true;

        // Check / recurse left
        if (!checkBST(n.left)) return false;

        // Check current
        if (n.data <= last_printed) return false;
        last_printed = n.data;

        // Check / recurse right
        if (!checkBST(n.right)) return false;

        return true; // All good!
}

现在,在这里一切都很好,但随后这本书引用:

If you don’t like the use of static variables, then you can tweak this code to use a wrapper class for the integer, as shown below:

Class WrapInt {
    public int value;
}     

在这里和其他网站上阅读包装类后,我无法得出结论,为什么以及如何在这里使用包装类而不是静态变量?

解决方法:

这是一种机制,您可以通过它创建WrapInt的实例并传递它.然后,您只将值公开给应该知道它的代码,而不是可以从任何地方访问和更改的公共静态非final变量.

你有包装类的原因是因为Java原语是按值传递的;传递一个int然后更新它不会通过系统的其余部分传播更改.

这看起来像这样:

public static boolean checkBST(TreeNode n) {
    WrapInt counter = new WrapInt();
    return checkBST(n, counter);
}

public static boolean checkBST(TreeNode n, WrapInt counter) {
    if(n == null) return true;

        // Check / recurse left
        if (!checkBST(n.left, counter)) return false;

        // Check current
        if (n.data <= counter.value) return false;
        counter.value = n.data;

        // Check / recurse right
        if (!checkBST(n.right, counter)) return false;

        return true; // All good!
}

标签:java,static,binary-tree,wrapper,binary-search-tree
来源: https://codeday.me/bug/20190519/1137764.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有