1. 程式人生 > 其它 >JAVA學習2021-07-24

JAVA學習2021-07-24

題目來源:226. 翻轉二叉樹

翻轉一棵二叉樹。

示例:

輸入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

輸出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 
*/ /** * @param {TreeNode} root * @return {TreeNode} */ var invertTree = function(root) { if(!root){ return null } let left = invertTree(root.left) let right = invertTree(root.right) root.left = right root.right = left return root };

Python3

# 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: TreeNode) -> TreeNode: if not root: return root left = self.invertTree(root.left) right
= self.invertTree(root.right) root.left, root.right = right, left return root