Title: Flipping binary trees


Computes the sum of all left leaves of a given binary tree.Copy the code

Example:


Input: 4 / \ 27 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1Copy the code

Think about:


This problem is recursive. Swap the left node of root with the right node, and then recursively swap the left and right nodes of the left node, and the left and right nodes of the right node.Copy the code

Implementation:


class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode temp = root.left; root.left = root.right; root.right = temp; invertTree(root.left); invertTree(root.right); return root; }}Copy the code