二叉树与递归方法
- 树的深度
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
- 是否对称
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
- 合并二叉树
public TreeNode mergeTrees(TreeNode t1, TreeNode t2){
if(t1==null) return t2;
if(t2==null) return t1;
int val=t1.val+t2.val;
TreeNode newNode=new TreeNode(val);
newNode.left=mergeTrees(t1.left, t2.left);
newNode.right=mergeTrees(t1.right, t2.right);
return newNode;
}
- 翻转二叉树
1.简易版本
public TreeNode invertTree(TreeNode root) {
if(root==null) return null;
TreeNode tmp=root.right;
root.right=root.left;
root.left=tmp;
root.left=invertTree(root.left);
root.right=invertTree(root.right);
return root;
}
2.较复杂的有栈版本
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
final TreeNode node = queue.poll();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}