您的位置:首页 > 其它

<LeetCode OJ> Invert Binary Tree【226】

2015-12-28 20:01 381 查看


226. Invert Binary Tree

My Submissions

Question

Total Accepted: 57653 Total
Submissions: 136144 Difficulty: Easy

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.

Subscribe to see which companies asked this question

Hide Tags
Tree

/**
 * 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;
        }else{
            //这样做将:树的底层先被真正交换,然后其上一层才做反转
            TreeNode* newleft = invertTree(root->right);
            TreeNode* newright = invertTree(root->left);
            root->left = newleft;
            root->right = newright;
            return root;
        }
    } 
};


参考资源:

【1】博客地址,http://www.cnblogs.com/ganganloveu/p/4640933.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: