226. Invert Binary Tree

来源:互联网 发布:c语言中stdlib 编辑:程序博客网 时间:2024/06/06 00:58

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1

我的解法:

/** * 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:    void Invert(TreeNode* root){         if(root){            TreeNode* temp = root->left;            root->left = root->right;            root->right = temp;            if(root->left)invertTree(root->left);            if(root->right)invertTree(root->right);        }else{            return;        }    }        TreeNode* invertTree(TreeNode* root) {        Invert(root);        return root;    }};
写的很臃肿,下面式别人的简洁的

Recursive

TreeNode* invertTree(TreeNode* root) {    if (root) {        invertTree(root->left);        invertTree(root->right);        std::swap(root->left, root->right);    }    return root;}下面这个是用栈实现的非迭代的。 
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;}