关键是要知道什么时候左子树被打印完了 用一个helper,when helper is null, it means the left subtree of the root is finished, the root is the top element in the stack 当helper是null的时候,当前的左都打完了,这个时候可以放右边的node进helper;最后栈空了,但是helper不是null,这个时候就可以pop打印了。
helper的意义:下一个要看的节点 如果不是null就入栈 如果是null就证明当前栈的top(左边)被打印完了,可以pop了,pop完helper里是刚才pop的节点的 right child 直到left和right都是空的时候停止
List<List<Integer>> graph //也可以 Array<Array<Integer>> 如果知道长度
graph.get(0) //里的list的长度就是0的neighbor的个数
graph.get(1)
for (Integer i:graph.get(1)) {
// i is a neighbor of node 1
}
class TreeNode {
int key;
TreeNode left;
TreeNode right;
public TreeNode(int key) {
this.key = key;
}
}
//recursion 尾递归 最后一步调用自身
public TreeNode searchInBST(TreeNode root, int value) {
if (root==null || root.key==target) { //没找到或者找到了的时候停止
return root;
}
if (root.key<value) {
return searchInBST(root.right, value);
}else {
return searchInBST(root.left, value);
}
}
//recursion 三目
public TreeNode biSearch(TreeNode root, int target) {
if (root == null || root.key == target) {
return root;
}
return biSearch(root.key > target ? root.left : root.right, target);
//iteration
public TreeNode searchInBST(TreeNode root, Integer value) {
while (root!=null && root.key!=target) { //root==null || root.key==target
if (root.key<value) {
root=root.right;
}else {
root = root.left;
}
return root
}