226. 翻转二叉树

https://leetcode-cn.com/problems/invert-binary-tree/

解法一:前序访问

也不知道怎么想出来的,原本觉得翻转二叉树应该用中序遍历(左中右),对应新树变为右中左即可,然而发现中序的话根节点无法正确建立,应该先建立根,再处理左右子树(前序).

于是算法思想为:前序递归遍历原树,然后新树(根为node)的右子树用原树的左子树建立,新树的左子树用原树的右子树建立,如此递归.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return
        node = TreeNode(root.val)    #建立新结点
        node.left = self.invertTree(root.right)
        node.right = self.invertTree(root.left)
        return node

js

var invertTree = function(root) {
  if (root) {
    let root1 = new TreeNode(root.val)
    root1.left = invertTree(root.right)
    root1.right = invertTree(root.left)
    return root1
  } else {
    return null
  }
};

最后更新于