合并二叉树
已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。例如:
两颗二叉树是:
解题思路:
要将一棵二叉树的节点与另一棵二叉树相加合并,肯定需要遍历两棵二叉树,那我们可以考虑同步遍历两棵二叉树,这样就可以将每次遍历到的值相加在一起。遍历的方式有多种,这里推荐前序递归遍历。
step 1:首先判断t1与t2是否为空,若为则用另一个代替,若都为空,返回的值也是空。
step 2:然后依据前序遍历的特点,优先访问根节点,将两个根点的值相加创建到新树中。
step 3:两棵树再依次同步进入左子树和右子树。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
// write code here
if(t1 == null) return t2;
if(t2 == null) return t1;
t1.val +=t2.val;
t1.left = mergeTrees(t1.left,t2.left);
t1.right = mergeTrees(t1.right,t2.right);
return t1;
}
}
二叉树的镜像
解题思路:
因为我们需要将二叉树镜像,意味着每个左右子树都会交换位置,如果我们从上到下对遍历到的节点交换位置,但是它们后面的节点无法跟着他们一起被交换,因此我们可以考虑自底向上对每两个相对位置的节点交换位置,这样往上各个子树也会被交换位置。
自底向上的遍历方式,我们可以采用后序递归的方法:
step 1:先深度最左端的节点,遇到空树返回,处理最左端的两个子节点交换位置。
step 2:然后进入右子树,继续按照先左后右再回中的方式访问。
step 3:再返回到父问题,交换父问题两个子节点的值。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot == null) {
return null;
}
if(pRoot.left!= null || pRoot.right != null) {
TreeNode temp = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = temp;
}else{
return pRoot;
}
pRoot.left = Mirror(pRoot.left);
pRoot.right = Mirror(pRoot.right);
return pRoot;
}
}