1. 程式人生 > >LeetCode226:Invert Binary Tree

LeetCode226:Invert Binary Tree

code 處理 split left pop oot div parent 有意義

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;
        }
       }

LeetCode226:Invert Binary Tree