剑指 Offer 32 - III. 从上到下打印二叉树 III
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//思路:整体队列+按行栈或者列表
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
int count=0;
while(!queue.isEmpty()){
count++;
List<Integer> temp=new ArrayList<>();
int n=queue.size();
//从左到右
if(count%2!=0){
while(n!=0){
TreeNode t1=queue.poll();
temp.add(t1.val);
if(t1.left!=null) queue.add(t1.left);
if(t1.right!=null) queue.add(t1.right);
n--;
}
res.add(temp);
}else{
Stack<Integer> stack=new Stack<>();
while(n!=0){
TreeNode t1=queue.poll();
stack.add(t1.val);
if(t1.left!=null) queue.add(t1.left);
if(t1.right!=null) queue.add(t1.right);
n--;
}
//注意对stack使用增强for来遍历stack,并不是按后进先出的顺序遍历
// for(int num:stack){
// temp.add(num);
// }
while(!stack.isEmpty()){
temp.add(stack.pop());
}
res.add(temp);
}
}
return res;
}
}
剑指 Offer 28. 对称的二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//思路:按照判定规则
//对称二叉树定义: 对于树中 任意两个对称节点 LL 和 RR ,一定有:
//1.此两对称节点值相等。
//2.即 LL 的 左子节点 和 RR 的 右子节点 对称;
//3.即 LL 的 右子节点 和 RR 的 左子节点 对称。
public boolean isSymmetric(TreeNode root) {
if(root==null) return true;
return isDc(root.left,root.right);
}
public boolean isDc(TreeNode l,TreeNode r){
if(l==null&&r==null) return true;
if(l==null||r==null||l.val!=r.val)
return false;
else return isDc(l.left,r.right)&&isDc(l.right,r.left);
}
}
剑指 Offer 27. 二叉树的镜像
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
//自己做时还是对如何进行左右节点的交换无头绪,
if(root==null) return root;
TreeNode temp_l=mirrorTree(root.left);
TreeNode temp_r=mirrorTree(root.right);
root.right=temp_l;
root.left=temp_r;
return root;
}
}