1 BFS( 127
)
广度优先遍历的最重要的数据结构是队列(queue),利用的就是先进先出的特性
如上图所示:对于广度优先遍历来说,遍历的流程如下所示:
- 1加入队列中,1出队列,将1的左节点2,右节点加入队列中
- 2出队列,将2的左节点4,右节点5加入队列
- 3出队列,将3的左节点6,右节点7加入队列
- 4出队列,4的左右节点都为空
- 5出队列,5的左右节点都为空
- 6出队列,6的左右节点都为空
- 7出队列,7的左右节点都为空
public void BFS(TreeNode node) {
if(node == null) return;
// 好像也可以使用ArrayDeque
// Queue<TreeNode> queue = new ArrayDeque<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node);
while(queue.peek() != null) {
TreeNode res = queue.poll();
sout(res.val);
if(res.left != null) {
queue.add(res.left);
}
if(res.right != null) {
queue.add(res.right);
}
}
}
2 DFS
深度优先遍历使用的是Stack的先进后出的特性
如上图所示:对于广度优先遍历来说,遍历的流程如下所示:
- 将节点1入栈,出栈访问右左子节点,将右节点3,左节点2入栈
- 节点2出栈,访问右左子节点,将右节点5,左节点4入栈
- 节点4出栈,4的孩子为空,没有入栈操作
- 节点5出栈,5的孩子为空,没有入栈操作
- 节点3出栈,访问右左子节点,将右节点7,左节点6入栈
- 节点6出栈,6的孩子为空,没有入栈操作
- 节点7出栈,7的孩子为空,没有入栈操作
public void DFS(TreeNode node) {
if(node == null) return;
Stack<TreeNode> st = new Stack<>();
st.push(node);
while(st.peek() != null) {
TreeNode res = st.pop();
sout(res.val);
if(res.right != null) {
st.push(res.right);
}
if(res.left != null) {
st.push(res.left);
}
}
}
131.分割回文串
3 二分查找
end = (end + start) / 2; // 这样写会导致越界的情况产生
end = start + (end - start) /2 // 避免越界的情况产生
5 LDR(中序遍历的实现)
LC:验证二叉搜索树
中序遍历:
public boolean isValidBST(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
long preOrder = Long.MIN_VALUE;
while(!stack.isEmpty() || root != null) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.val <= preOrder) return false;
preOrder = root.val;
root = root.right;
}
}
递归实现:
public boolean isValidBST(TreeNode root) {
return recursion(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean recursion(TreeNode node, Long min, Long max) {
// 判断条件
...
return recursion(node.left, min, node.val) && recursion(node.right, node.val, max);
}