Invert Binary Tree

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;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    struct TreeNode *left, *right;
    if(root == NULL)
        return NULL;
    else if(root->left == NULL && root->right == NULL)
        return root;
    else
        {
            left = invertTree(root->right);    //这里必须保存到left这个临时变量中
            right = invertTree(root->left);    //否则下一次的翻转会失效
            root->left = left;
            root->right = right;
            return root;
        }
}
  • 注意,这里的left和right必须是另外设置的临时变量;如果直接使用root->left和root->right会导致第一次转过来了,第二次又转回去
posted @ 2015-10-15 08:51  dylqt  阅读(115)  评论(0编辑  收藏  举报