文章目录
3. 层序遍历二叉树
题目链接:102. 二叉树的层序遍历 - 力扣(LeetCode)
BFS
裸题:对头(根)先入队,当队列不为空时,(遍历此时队列中的所有元素)对头元素逐一出队(队头出),加入答案(每一层),的元素,然后将该元素的左右儿子入队(队尾入),当前层遍历完后,将这层的答案记录,进入下一层。直到最后队列为空
Code
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
List<Integer> ceng = new ArrayList<>();
int len = q.size();
for(int i = 0; i < len; i ++){
TreeNode t = q.poll();
ceng.add(t.val);
if(t.left != null) q.add(t.left);
if(t.right != null) q.add(t.right);
}
res.add(ceng);
}
return res;
}
}
4. 翻转二叉树
题目链接:226. 翻转二叉树 - 力扣(LeetCode)
思路:递归实现
- 如果根节点不为空,那么就要交换其左右子树(即使左右子树是空节点也没关系)
- 递归交换左右子树
Code
class Solution {
public TreeNode invertTree(TreeNode root) {
dfs(root);
return root;
}
public static void dfs(TreeNode root){
if(root == null){
return ;
}
// 交换
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
dfs(root.left);
dfs(root.right);
}
}
5. 对称二叉树
题目链接:101. 对称二叉树 - 力扣(LeetCode)
解法一 递归:同时遍历左右子树,左右子树是否完全对称
- 两个根节点的值要相等
- 左边的左子树和右边的右子树对称
- 左边的右子树和右边的左子树对称
Code
class Solution {
public boolean isSymmetric(TreeNode root) {
return dfs(root.left, root.right);
}
public static boolean dfs(TreeNode l, TreeNode r){
if(l == null && r == null) return true;
if(l == null || r == null) return false;
if(l.val != r.val) return false;
return dfs(l.left, r.right) && dfs(l.right, r.left);
}
}
解法二 迭代:
- 左边的树按
左中右
的顺序遍历 - 右边的树按
右中左
的顺序遍历 - 同时遍历,遍历的同时判断值是否相同(每次遍历都是一一对应的两个点)
栈来迭代模拟上述递归遍历的过程!
Code
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Stack<TreeNode> left = new Stack<>();// 左树
Stack<TreeNode> right = new Stack<>();// 右树
TreeNode lc = root.left;
TreeNode rc = root.right;
// 左边的树:左中右
// 右边的树:右中左
while(lc != null || rc != null || !left.empty()){
// 同时遍历
while(lc != null && rc != null){
//左树: 一直左
left.push(lc);
lc = lc.left;
//右树: 一直右
right.push(rc);
rc = rc.right;
}
if(lc == null && rc != null || lc != null && rc == null) return false;
//左右树: 中 ()
lc = left.pop();
rc = right.pop();
if(lc.val != rc.val) return false;
//左树: 右
lc = lc.right;
//右树: 左
rc = rc.left;
}
return true;
}
}