二叉树
二叉树的遍历(递归)
public void traverse(TreeNode root) {
traverse(root.left);
traverse(root.right);
}
二叉树的遍历(非递归)
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()){
while(root != null){
........
stack.push(root);
root = root.left;
}
root = stack.pop();
........
root = root.right;
}
return list;
}
针对 二叉搜索树 的元素查找
void BST(TreeNode root, int target) {
if (root.val == target)
if (root.val < target)
BST(root.right, target);
if (root.val > target)
BST(root.left, target);
}