題目
請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。
例如輸入:
? ? ?4
? ?/ ? \
? 2 ? ? 7
?/ \ ? / \
1 ? 3 6 ? 9
鏡像輸出:
? ? ?4
? ?/ ? \
? 7 ? ? 2
?/ \ ? / \
9 ? 6 3? ?1
示例 1:
輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]
限制:
0 <= 節(jié)點個數 <= 1000
解題思路
1.題目要求我們設計函數輸一個樹結構的鏡像,對于這個問題我們采用遞歸的方法來解決,
2,首先我們先寫出結束條件,當root == null,或者 root 的左右節(jié)點都為 null 時,我們直接返回 root,
3.然后我們遞歸的調用 mirrorTree()方法,將 root 的左右子樹交給 mirrorTree()方法去實現鏡像,我們需要做的就是將 mirrorTree()方法已經實現好的左右子樹交換一下位置,讓 root 的左子樹等于 右子樹,讓 root 的右子樹等于左子樹即可。
代碼實現
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null || root.left == null && root.right == null){
return root;
}
TreeNode left = mirrorTree(root.left);
TreeNode right = mirrorTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
測試結果
文章來源:http://www.zghlxwxcb.cn/news/detail-645980.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-645980.html
到了這里,關于Leetcode-每日一題【劍指 Offer 27. 二叉樹的鏡像】的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!