102.二叉树的层序遍历
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-level-order-traversal
队列存放当前一层二叉树的元素,队列不为空时,记录队列大小size,把队列的前size个元素poll出来,如果该元素的左子树和右子树不为空,加入到队列尾。
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(root==null) return res;
Queue<TreeNode>queue=new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
int size=queue.size();
List<Integer> tres=new ArrayList<>();
while(size-->0) {
TreeNode cur=queue.poll();
tres.add(cur.val);
if(cur.left!=null) queue.add(cur.left);
if(cur.right!=null) queue.add(cur.right);
}
res.add(tres);
}
return res;
}
226.翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/invert-binary-tree
按前序遍历节点,每遍历到一个节点,翻转节点的左子树和右子树。
public TreeNode invertTree(TreeNode root) {
if(root==null) return null;
Stack<TreeNode>stack=new Stack<>();
stack.add(root);
while(!stack.isEmpty()) {
TreeNode cur=stack.pop();
TreeNode t=cur.left;
cur.left=cur.right;
cur.right=t;
if(cur.right!=null) stack.add(cur.right);
if(cur.left!=null) stack.add(cur.left);
}
return root;
}
101. 对称二叉树
给你一个二叉树的根节点
root
, 检查它是否轴对称。示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
root的左子树和右子树作为两个树进行对比,对比左子树的左节点和右子树的右节点,以及左子树的右节点和右子树的左节点。
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public boolean compare(TreeNode r1,TreeNode r2) {
if(r1==null&&r2==null) return true;
else if(r1==null&&r2!=null) return false;
else if(r1!=null&&r2==null) return false;
else if(r1.val!=r2.val) return false;
return compare(r1.left,r2.right)&&compare(r1.right,r2.left);
}