首页 > 代码库 > LeetCode226:Invert Binary Tree

LeetCode226:Invert Binary Tree

nvert a binary tree.

技术分享
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.
Hide Tags Tree

尽管不知道Homebrew为何物,可是google 90%的人都用的产品绝对是高大上的。所以估且把这个trivia当成Max Howell在卖萌吧。


解法一

反转二叉树使用递归实现,能够看出,假设把左子树和右子树都反转了的话。仅仅须要交换它的左右子树节点就能够了。而反转子树和反转它自身是同一个问题,所以能够使用递归实现。
runtime:4ms

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)
            return NULL;
        TreeNode * leftTree=NULL;
        TreeNode * rightTree=NULL;
        if(root->left)
            leftTree=invertTree(root->left);
        if(root->right)
            rightTree=invertTree(root->right);
        root->left=rightTree;
        root->right=leftTree;
        return root;
    }
};

解法二

这道题还能够使用非递归来实现,非递归实现代码可能会多了一点,可是也非常好理解。使用一个队列,開始时将根节点增加队列中,然后交换它的左右子节点并将根节点从队列中弹出,假设左右子节点非空。将左右子节点增加队列中。一直处理到队列中没有元素为止。參考的解答:https://leetcode.com/discuss/40567/my-c-codes-recursive-and-nonrecursive
runtime:0ms
从执行时间能够看出研究一下非递归的解法还是非常有意义的。

   class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            queue<TreeNode *> tbpNode;
            if(root) tbpNode.push(root);
            TreeNode *curNode, *temp;
            while(!tbpNode.empty())
            {
                curNode = tbpNode.front();
                tbpNode.pop();
                temp = curNode->left;
                curNode->left = curNode->right;
                curNode->right = temp;
                if(curNode->left) tbpNode.push(curNode->left);
                if(curNode->right) tbpNode.push(curNode->right);
            }
            return root;
        }
       }
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

LeetCode226:Invert Binary Tree