Tree - 226. Invert Binary Tree

时间:2022-07-25
本文章向大家介绍Tree - 226. Invert Binary Tree,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

226. Invert Binary Tree

Invert a binary tree.

Example:

Input:

     4
   /   
  2     7
 /    / 
1   3 6   9

Output:

     4
   /   
  7     2
 /    / 
9   6 3   1

思路:

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

代码:

go:

/**

 * 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
}