gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:40 24 4
gpt4 key购买 nike

这是我在 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.

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

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 实例并将其传递。然后,您仅将该值公开给应该知道它的代码,而不是可以从任何地方访问和更改的公共(public)静态非最终变量。

您拥有包装器类的原因是因为 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 - 使用包装类而不是静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29770749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com