題目描述
題目轉載自Leetcode
請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。
例如輸入:
示例 1:
輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]
題解 遞歸法
題解轉載自leetcode作者Krahets
根據二叉樹鏡像的定義,考慮遞歸遍歷(dfs)二叉樹,交換每個節點的左 / 右子節點,即可生成二叉樹的鏡像。
遞歸解析:
終止條件: 當節點 root 爲空時(即越過葉節點),則返回 null ;
遞推工作:
初始化節點 tmp ,用於暫存 root 的左子節點;
開啓遞歸 右子節點 mirrorTree(root.right) ,並將返回值作爲 root 的 左子節點 。
開啓遞歸 左子節點 mirrorTree(tmp) ,並將返回值作爲 root 的 右子節點 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right=mirrorTree(tmp);
return root;
}
}