劍指 Offer 27. 二叉樹的映象
知識點:二叉樹;遞迴;棧
題目描述
請完成一個函式,輸入一個二叉樹,該函式輸出它的映象。
示例
輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]
解法一:遞迴法
函式功能:二叉樹映象;
1、終止條件:root==null的時候,返回null;
2、每個節點該做什麼:將兩個孩子節點互換;
3、什麼時候做:遞去的時候或者回來的時候都行(前序或者後序都行)
/**
* 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 temp = root.right;
root.right = root.left;
root.left = temp;
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
}
時間複雜度;0(N),每個節點恰好被遍歷一次;
空間複雜度;O(N),遞迴過程中棧的開銷;
解法二:棧
自己構造一個輔助棧,依次遍歷所有的節點,並交換每個節點的左右孩子;
規則:
壓入根節點;
1.彈出;
2.壓入彈出節點的左右孩子,並交換;
其實是一層一層,一個節點一個節點的處理。
/**
* 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;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode top = stack.pop();
if(top.left != null) stack.push(top.left);
if(top.right != null) stack.push(top.right);
TreeNode temp = top.left;
top.left = top.right;
top.right = temp;
}
return root;
}
}
時間複雜度;0(N),每個節點恰好被遍歷一次;
空間複雜度;O(N),遞迴過程中棧的開銷