[LeetCode]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.

思路:交换左右子节点,递归解决。 非递归用栈解决。

小伙伴快来试试看下谷歌是否有戏~~_(:зゝ∠)__(:зゝ∠)__(:зゝ∠)__(:зゝ∠)_

递归

/**
 * 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) {
        TreeNode *res = root;
        recursion(root);
        return res;
    }
    void recursion(TreeNode *root){
        if(root==NULL)
            return;
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        invertTree(root->left);
        invertTree(root->right);
    }
};


非递归

/**
 * 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==nullptr)
            return nullptr;
        stack<TreeNode*> stk;
        TreeNode *res = root;
        stk.push(root);
        while(!stk.empty()){
            TreeNode* node = stk.top();
            stk.pop();
            if(node->left||node->right){ //非叶节点
                TreeNode* temp = node->left;
                node->left = node->right;
                node->right = temp;
            }
            if(node->left)//注意空指针
                stk.push(node->left);
            if(node->right)
                stk.push(node->right);
        }
        return res;
    }
};


你可能感兴趣的:([LeetCode]Invert Binary Tree)