二叉树简单题|对称、翻转、合并二叉树
文章目录
二叉树简单题|对称、翻转、合并二叉树 模板代码 101 对称二叉树 226 翻转二叉树 617 合并二叉树
模板代码
private boolean process ( TreeNode p, TreeNode q) {
if ( p == null && q == null ) {
return ;
} else if ( p == null && q != null ) {
return ;
} else if ( p != null && q == null ) {
return ;
} else {
return ;
}
}
101 对称二叉树
public class $101 {
public boolean isSymmetric ( TreeNode root) {
if ( root == null ) {
return false ;
}
return process ( root. left, root. right) ;
}
private boolean process ( TreeNode p, TreeNode q) {
if ( p == null && q == null ) {
return true ;
} else if ( p == null && q != null ) {
return false ;
} else if ( p != null && q == null ) {
return false ;
} else {
return p. val == q. val && process ( p. left, q. right) && process ( p. right, q. left) ;
}
}
}
226 翻转二叉树
import java. util. LinkedList ;
import java. util. List ;
public class $226 {
public TreeNode invertTree ( TreeNode root) {
if ( root == null ) {
return null ;
}
return process ( root) ;
}
private TreeNode process ( TreeNode root) {
if ( root. left == null && root. right == null ) {
return root;
} else if ( root. left == null && root. right != null ) {
TreeNode rigRes = process ( root. right) ;
root. left = rigRes;
root. right = null ;
return root;
} else if ( root. left != null && root. right == null ) {
TreeNode lefRes = process ( root. left) ;
root. right = lefRes;
root. left = null ;
return root;
} else {
TreeNode lefRes = process ( root. left) ;
TreeNode rigRes = process ( root. right) ;
root. left = rigRes;
root. right = lefRes;
return root;
}
}
}
617 合并二叉树
public class $617 {
public TreeNode mergeTrees ( TreeNode root1, TreeNode root2) {
return process ( root1, root2) ;
}
private TreeNode process ( TreeNode p, TreeNode q) {
if ( p == null && q == null ) {
return null ;
} else if ( p == null && q != null ) {
return q;
} else if ( p != null && q == null ) {
return p;
} else {
TreeNode node = new TreeNode ( p. val + q. val) ;
node. left = process ( p. left, q. left) ;
node. right = process ( p. right, q. right) ;
return node;
}
}
}