這道題很簡單,寫了十多分鐘就寫出來了,一看題目就知道這道題肯定要用遞歸。先交換左孩子和右孩子,再用遞歸交換左孩子的左孩子和右孩子,交換右孩子的左孩子和右孩子,其中做一下空判斷就行。以下是我的代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-522113.html
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return root;
}else{
return recur(root);
}
}
public TreeNode recur(TreeNode root){
TreeNode temp = new TreeNode();
if(root.left != null && root.right !=null){
temp = root.right;
root.right = root.left;
root.left = temp;
}else if(root.left == null && root.right != null){
root.left = root.right;
root.right = null;
}else if(root.left != null && root.right == null){
root.right = root.left;
root.left = null;
}
if(root.left != null) recur(root.left);
if(root.right != null) recur(root.right);
return root;
}
}
看了一下題解大多數(shù)用的遞歸,還有用輔助棧的。文章來源地址http://www.zghlxwxcb.cn/news/detail-522113.html
到了這里,關(guān)于劍指offer27.二叉樹的鏡像的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!