226. Invert Binary Tree

来源:互联网 发布:js将字符串转化成数字 编辑:程序博客网 时间:2024/06/04 19:44

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.

我的笨方法:DFS

/** * 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* p_left=invertTree(root->left);        TreeNode* p_right=invertTree(root->right);        root->left=p_right;        root->right=p_left;                return root;    }};

改进DFS

/** * 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) {        invertTree(root->left);        invertTree(root->right);        std::swap(root->left, root->right);    }    return root;    }};

利用栈或队列的BFS

/** * 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) {        std::stack<TreeNode*> stk;        stk.push(root);            while (!stk.empty()) {            TreeNode* p = stk.top();            stk.pop();            if (p) {                stk.push(p->left);                stk.push(p->right);                std::swap(p->left, p->right);            }        }        return root;    }};

TreeNode* invertTree(TreeNode* root) {    if(nullptr == root) return root;    queue<TreeNode*> myQueue;   // our queue to do BFS    myQueue.push(root);         // push very first item - root    while(!myQueue.empty()){    // run until there are nodes in the queue         TreeNode *node = myQueue.front();  // get element from queue        myQueue.pop();                     // remove element from queue        if(node->left != nullptr){         // add left kid to the queue if it exists            myQueue.push(node->left);        }        if(node->right != nullptr){        // add right kid             myQueue.push(node->right);        }        // invert left and right pointers              TreeNode* tmp = node->left;        node->left = node->right;        node->right = tmp;    }    return root;} 



0 0