二叉树的遍历:
力扣226,101,222,110
1.二叉树的反转226
递归法:
if(root==null){
return root;
}
reverseChildren(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
private void reverseChildren(TreeNode root){
TreeNode temp= root.right;
root.right=root.left;
root.left=temp;
}
迭代法
if(root==null){
return true;
}
Deque<TreeNode>queue = new LinkedList<>();
queue.addFirst(root.left);
queue.addLast(root.right);
while (!queue.isEmpty()){
TreeNode node1 = queue.pollFirst();
TreeNode node2 = queue.pollLast();
if(node1==null&&node2==null){
continue;
}
if(node1==null||node2==null||node1.val!=node2.val){
return false;
}
queue.addFirst(node1.right);
queue.addLast(node2.left);
queue.addFirst(node1.left);
queue.addLast(node2.right);
}
return true;
2.对称二叉树101
递归法
if(root==null){
return true;
}
return mirrorTree(root.left,root.right);
}
private boolean mirrorTree(TreeNode left,TreeNode right){
if(left!=null&&right==null){
return false;
}else if(left==null&&right!=null){
return false;
}else if(left==null&&right==null){
return true;
}
else if(left.val!=right.val){
return false;
}
boolean outside = mirrorTree(left.left, right.right);
boolean inside = mirrorTree(left.right, right.left);
return outside&&inside;
3.二叉树的节点个数
if(root==null){
return 0;
}
int leftCount = countNodes(root.left);
int rightCount = countNodes(root.right);
return 1+leftCount+rightCount;
4.平衡二叉树
if(root==null){
return true;
}
getMaxDepth(root);
return res;
}
private int getMaxDepth(TreeNode root){
if(root==null){
return 0;
}
int leftDepth = getMaxDepth(root.left);
int rightDepth = getMaxDepth(root.right);
if(Math.abs(leftDepth-rightDepth)>=2){
res=false;
}
return 1+Math.max(leftDepth,rightDepth);