问题描述:
代码:
class Solution {
public boolean isValidBST(TreeNode root) {
double inorder = -Double.MAX_VALUE;
Deque<TreeNode> stk = new LinkedList<>();
while(!stk.isEmpty()||root!=null){
while(root!=null){
stk.push(root);
root=root.left;
}
root = stk.pop();
if(root.val<=inorder)
return false;
inorder=root.val;
root=root.right;
}
return true;
}
}
思路:
问题描述:
代码:
class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> hx = new HashSet<>();
Deque<TreeNode> stk = new LinkedList<>();
while(root!=null||!stk.isEmpty()){
while(root!=null){
stk.push(root);
root=root.left;
}
root=stk.poll();
if(hx.contains(k-root.val))
{
return true;
}
else{
hx.add(root.val);
}
root=root.right;
}
return false;
}
}
思路:
HashSet
问题描述:
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> treep = getPath(root,p);
List<TreeNode> treeq = getPath(root,q);
TreeNode ancestor = null;
for (int i = 0; i < treep.size() && i < treeq.size(); ++i) {
if (treep.get(i) == treeq.get(i)) {
ancestor = treep.get(i);
} else {
break;
}
}
return ancestor;
}
public List<TreeNode> getPath(TreeNode root, TreeNode target) {
List<TreeNode> tree = new LinkedList<>();
while(true){
if(root.val>target.val)
{
tree.add(root);
root=root.left;
}else if(root.val<target.val){
tree.add(root);
root=root.right;
}else{
tree.add(target);
break;
}
}
return tree;
}
}
思路: