1、合并二叉树
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) {
return null;
}
if(t1 == null) {
return t2;
}
if(t2 == null) {
return t1;
}
//新的节点
t1.val = t1.val + t2.val;
t1.left = mergeTrees(t1.left,t2.left);
t1.right = mergeTrees(t1.right,t2.right);
return t1;
}
}
2、二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) {
return null;
}
if(root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left != null && right != null) {
return root;
}
if(left != null) {
return left;
}
if(right != null) {
return right;
}
return null;
}
}
3、二叉树的完全性检验
给定一个二叉树,确定它是否是一个完全二叉树。
class Solution {
public boolean isCompleteTree(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur != null) {
queue.offer(cur.left);
queue.offer(cur.right);
} else {
break;
}
}
while (!queue.isEmpty()) {
TreeNode cur = queue.peek();
if (cur != null) {
return false;
}else {
queue.poll();
}
}
return true;
}
}
4、递增顺序查找树
给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
class Solution {
public TreeNode increasingBST(TreeNode root) {
if (root == null) return null;
TreeNode leftRoot = increasingBST(root.left);
TreeNode rightRoot = increasingBST(root.right);
if (leftRoot != null) {
TreeNode cur = leftRoot;
while (cur != null && cur.right != null) {
cur = cur.right;
}
cur.right = root;
}
root.left = null;
root.right = rightRoot;
return leftRoot == null ? root : leftRoot;
}
}