标签:
Invert a binary tree.
4 / 2 7 / \ / 1 3 6 9to
4 / 7 2 / \ / 9 6 3 1Trivia:
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.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 struct TreeNode* invertTree(struct TreeNode* root) { 10 if (root == NULL) 11 return root; 12 if (root->left == NULL && root->right == NULL) 13 return root; 14 else{ 15 struct TreeNode* temp = root->right; 16 root->right = root->left; 17 root->left = temp; 18 } 19 root->left = invertTree(root->left); 20 root->right = invertTree(root->right); 21 22 return root; 23 }
下面是在网上找的一种解法,C++写的。由于这是对实际树的结构进行操作,所以说可以不特别管返回值。
1 TreeNode* invertTree(TreeNode* root) { 2 if (root) { 3 invertTree(root->left); 4 invertTree(root->right); 5 std::swap(root->left, root->right); 6 } 7 return root; 8 }
标签:
原文地址:http://www.cnblogs.com/QingHuan/p/5042502.html