226. Invert Binary Tree(unsolved)

来源:互联网 发布:淘宝一元拍卖 编辑:程序博客网 时间:2024/06/06 03:23

Invert a binary tree.

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

to

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

方法一:递归

思路:深度优先搜索,用递归的方式,交换完root的左右后,交换root左右子树的左右子树。

/** * 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;        TreeNode*temp=root->left;        root->left=root->right;        root->right=temp;        invertTree(root->left);        invertTree(root->right);        return root;    }};

方法二:迭代
思想:使用广度优先搜索,设立一个队列,每次都把一个节点压进去,然后调换其左右节点,把其左右节点压进去后,再把这个节点弹出来

/** * 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;        queue<TreeNode*> p;        p.push(root);        while(!p.empty())        {            swap(p.front()->left,p.front()->right);            if(p.front()->right)                p.push(p.front()->right);            if(p.front()->left)                p.push(p.front()->left);            p.pop();        }        return root;    }};
0 0
原创粉丝点击