iT邦幫忙

2022 iThome 鐵人賽

DAY 14
0

題目說明:給一棵二元樹,要你反轉這棵樹並且回傳此樹的root

Case 1

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Case 2

Input: root = [2,1,3]
Output: [2,3,1]

Case 3
Input: root = []
Output: []

解題思路:何謂反轉?從上面的例子來看,就可以知道就是左子樹和右子樹整個交換

放上程式碼和註解

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        reverse(root);
        return root;
    }
    public void reverse(TreeNode root){
        if (root == null)return;//如果樹的根節點為null,直接回傳
        
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;//將樹的左右節點交換
        
        reverse(root.left);//反轉root的左子樹
        reverse(root.right);//反轉root的右子樹
    }
}

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root==None:
            return 
        root.left,root.right=root.right,root.left#左右子樹交換
        self.invertTree(root.left)#反轉左子樹
        self.invertTree(root.right)#反轉右子樹
        return root

上一篇
Day 13 Sort Colors
下一篇
Day 15 Set Matrix Zeroes
系列文
從leetcode學習資料結構和演算法31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言