LeetCode 102.层序遍历
题目链接:https://leetcode.cn/problems/binary-tree-level-order-traversal/submissions/533807231/
文章链接:https://programmercarl.com/0102.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86.html#_102-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86
思路
* 层次遍历:借用队列作为辅助
* 1、根节点入队
* 2、队列不空,则循环
* 3、将队列里面的所有元素依次弹出,并访问,若有左孩子,左孩子入队,若有右孩子,右孩子入队
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> que = new LinkedList<>();
List<List<Integer>> resList = new ArrayList<List<Integer>>();
if (root == null)
return resList;
que.offer(root);
while (!que.isEmpty()){
List<Integer> itemList = new ArrayList<>();
int len = que.size();
while (len >0){
TreeNode tmpNode = que.poll();
itemList.add(tmpNode.val);
if (tmpNode.left != null)
que.offer(tmpNode.left);
if (tmpNode.right != null)
que.offer(tmpNode.right);
len--;
}
resList.add(itemList);
}
return resList;
}
LeetCode 226.翻转二叉树
题目链接:https://leetcode.cn/problems/invert-binary-tree/submissions/533809586/
文章链接:https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
思路
* 思路:采用后续遍历的思想
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
invertTree(root.left);
invertTree(root.right);
TreeNode tmpNode = root.left;
root.left = root.right;
root.right = tmpNode;
return root;
}
LeetCode 101. 对称二叉树
题目链接:https://leetcode.cn/problems/symmetric-tree/
文章链接:https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E6%80%9D%E8%B7%AF
思路
* 思路:首先想清楚,判断对称二叉树要比较的是哪两个节点,要比较的可不是左右节点!
* 对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的
* 也就是说我们可以将根节点的右子树整体做一个翻转,然后比较根节点的左子树和根节点的右子树是否相同即可
public boolean isSymmetric(TreeNode root) {
// 将右子树翻转
TreeNode rightRoot = invertTree(root.right);
return compare(root.left, rightRoot);
}
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
invertTree(root.left);
invertTree(root.right);
TreeNode tmpNode = root.left;
root.left = root.right;
root.right = tmpNode;
return root;
}
public boolean compare(TreeNode left, TreeNode right){
if (left == null && right == null)
return true;
else if (left == null || right == null)
return false;
else {
if (left.val != right.val)
return false;
else
return compare(left.left,right.left) && compare(left.right,right.right);
}
}