Fork me on GitHub

[leetcode-226-Invert Binary Tree]

Invert a binary tree.
      4
     / \
    2 7
  / \ / \
 1 3 6 9
to
    4
   / \
  7 2
 / \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

思路:
递归交换树左右结点即可。

void invertCore(TreeNode* root)
     {
         if (root == NULL) return;
         swap(root->left, root->right);
         invertCore(root->left);
         invertCore(root->right);
     }
     TreeNode* invertTree(TreeNode* root)
     {
         invertCore(root);
         return root;
     }

 

posted @ 2017-05-17 21:14  hellowOOOrld  阅读(97)  评论(0编辑  收藏  举报