[leetcode]-226. Invert Binary Tree

Invert a binary tree.

Example:

Input:

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

Output:

     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* t;
    if(root==NULL||(root->left==NULL&&root->right==NULL))
        return root;
    else
    {
        t=root->left;
        root->left=root->right;
        root->right=t;
    }
    invertTree(root->left);
    invertTree(root->right);
    return root;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/81282664