Tree - 226. Invert Binary Tree

2020-09-23 17:23:54 浏览数 (1)

226. Invert Binary Tree

Invert a binary tree.

Example:

Input:

代码语言:javascript复制
     4
   /   
  2     7
 /    / 
1   3 6   9

Output:

代码语言:javascript复制
     4
   /   
  7     2
 /    / 
9   6 3   1

思路:

递归求解翻转每个不为nil的节点

代码:

go:

代码语言:javascript复制
/**

 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
    if root == nil { return root }
    
    root.Left, root.Right = root.Right, root.Left
    invertTree(root.Left)
    invertTree(root.Right)
    
    return root
}

0 人点赞