【LeetCode】226. Invert Binary Tree

来源:互联网 发布:ae2017汉化补丁 mac 编辑:程序博客网 时间:2024/05/01 12:59

Question

Invert a binary tree.

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

to

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

Code

BFS:

/** * 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 root;        queue<TreeNode*> q;        q.push(root);        while (!q.empty()) {            TreeNode* cur = q.front();            q.pop();            TreeNode* tmp = cur->left;            cur->left = cur->right;            cur->right = tmp;            if (cur->left)  q.push(cur->left);            if (cur->right) q.push(cur->right);        }        return root;    }};

There is a simple recursion solution:

TreeNode* invertTree(TreeNode* root) {    if (root==NULL) return NULL;    TreeNode* tmp = root->left;    root->left = invertTree(root->right);    root->right = invertTree(tmp);    return root;}

Note

Be careful for the NULL pointer!

When you use a pointer, please make sure that it is availble!

0 0