problem
code
solution1-DFS
/** * 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* tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; } };
solution2-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 NULL; queue<TreeNode*> myqueue; myqueue.push(root); while(!myqueue.empty()) { TreeNode* node = myqueue.front(); myqueue.pop(); TreeNode* tmp = node->left; node->left = node->right; node->right = tmp; if(node->right)myqueue.push(node->right); if(node->left) myqueue.push(node->left); } return root; } };
参考
1. Leetcode_226-invert-binary-tree;
完