226. Invert Binary Tree
Contents
Problem
Invert a binary tree.
example 1
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1Solution
DFS ( recursive)
Main idea is dfs – change children.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return root
}
root.Right, root.Left = invertTree(root.Left), invertTree(root.Right)
return root
}