// 二叉树的中序非递归遍历
public static void medOrderUnRecur(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
while (!stack.empty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
System.out.print(root.data+" ");
root = root.right;
}
}
System.out.println();
}
leetcode 98 验证二叉搜索树
一开始想到二叉搜索树按照中序遍历的话是一个递增序列 只要比较两个顶点的大小,小于的话就返回false,否则往右走,但提交的时候报了错..没搞懂 后面看了下别人的思路,用的是递归版本
double last = -Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (isValidBST(root.left)) {
if (last < root.val) {
last = root.val;
return isValidBST(root.right);
}
}
return false;
}
下面是非递归版本
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
int preData = Integer.MIN_VALUE;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.empty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode node = stack.pop();
if (node.val < preData) {
return false;
} else {
preData = node.val;
}
root = node.right;
}
}
return true;
}