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:
方法一:递归
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* invertTree(TreeNode* root) { 13 if(root) 14 { 15 invertTree(root->left); 16 invertTree(root->right); 17 swap(root->left,root->right); 18 } 19 return root; 20 } 21 };
方法二:非递归,栈
1 class Solution { 2 public: 3 TreeNode* invertTree(TreeNode* root) { 4 stack<TreeNode*>stk; 5 stk.push(root); 6 while(!stk.empty()) 7 { 8 TreeNode*tmp=stk.top(); 9 stk.pop(); 10 if(tmp)//tmp可能为空 11 { 12 stk.push(tmp->left); 13 stk.push(tmp->right); 14 swap(tmp->left,tmp->right); 15 } 16 17 } 18 return root; 19 } 20 };