女人每个时期有每个时期的美,婚姻幸福更是女人最好的保养品......# Fashion - 美丽时尚
n*p
1 楼
in order traversal
要用一个变量来存前一个Node的值。但发现有时候值没有被更新,结果是错的,是因为
Java的passing by value的原因吗?代码如下:
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null) return true;
//if (root.left == null && root.right == null) return true;
Integer preVal = Integer.MIN_VALUE;
return inOrder (root, preVal);
}
public boolean inOrder(TreeNode root, Integer preVal) {
if (root == null) return true;
if (!inOrder(root.left, preVal)) return false;
if (preVal >= root.val) {
return false;
} else {
preVal = root.val;
}
if (!inOrder(root.right, preVal)) return false;
return true;
}
如果用Array的一个cell来存就解决了这个问题,但比较ugly。代码:
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null)
return true;
// if (root.left == null && root.right == null) return true;
int[] preVal = new int[1];
preVal[0] = Integer.MIN_VALUE;
return inOrder(root, preVal);
}
public boolean inOrder(TreeNode root, int[] preVal) {
if (root == null)
return true;
if (!inOrder(root.left, preVal))
return false;
if (preVal[0] >= root.val) {
return false;
} else {
preVal[0] = root.val;
}
if (!inOrder(root.right, preVal))
return false;
return true;
}
有什么好办法来解决这个问题?
要用一个变量来存前一个Node的值。但发现有时候值没有被更新,结果是错的,是因为
Java的passing by value的原因吗?代码如下:
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null) return true;
//if (root.left == null && root.right == null) return true;
Integer preVal = Integer.MIN_VALUE;
return inOrder (root, preVal);
}
public boolean inOrder(TreeNode root, Integer preVal) {
if (root == null) return true;
if (!inOrder(root.left, preVal)) return false;
if (preVal >= root.val) {
return false;
} else {
preVal = root.val;
}
if (!inOrder(root.right, preVal)) return false;
return true;
}
如果用Array的一个cell来存就解决了这个问题,但比较ugly。代码:
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null)
return true;
// if (root.left == null && root.right == null) return true;
int[] preVal = new int[1];
preVal[0] = Integer.MIN_VALUE;
return inOrder(root, preVal);
}
public boolean inOrder(TreeNode root, int[] preVal) {
if (root == null)
return true;
if (!inOrder(root.left, preVal))
return false;
if (preVal[0] >= root.val) {
return false;
} else {
preVal[0] = root.val;
}
if (!inOrder(root.right, preVal))
return false;
return true;
}
有什么好办法来解决这个问题?