[RainbowSecret] 2 C++ implementaion


  • 6

    recursive way

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            if(!root || (!root->left && !root->right))  return root;
            TreeNode* left=root->left, *right=root->right;
            root->right = invertTree(left);
            root->left = invertTree(right);
            return root;
        }
    };
    

    non-recursive way

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            stack<TreeNode*> st;
            st.push(root);
            while(!st.empty()){
                TreeNode* temp=st.top();
                st.pop();
                if(temp){
                    st.push(temp->left);
                    st.push(temp->right);
                    swap(temp->left, temp->right);
                }
            }
            return root;
        }
    };

  • 0
    F
    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            deque<TreeNode*> dq;
            dq.push_back(root);
            while (!dq.empty()) {
                TreeNode* cur = dq.front();
                dq.pop_front();
                if (cur) {
                    dq.push_back(cur->left);
                    dq.push_back(cur->right);
                    swap(cur->left, cur->right);
                }
            }
            return root;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.