文章 224
评论 6
浏览 200766
Tree - 226. Invert Binary Tree

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
}

标题:Tree - 226. Invert Binary Tree
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/18/1566130810760.html

Nothing just happens, it's all part of a plan.

取消