Invert Binary Tree
Total Accepted: 54994 Total Submissions: 130742 Difficulty: Easy
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:
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.
通过这道题,好好理解了递归。
递归返回的是什么要考虑清楚,
可以仔细研磨这道题,很好的题。
C语言
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 }
时间: 2024-10-13 12:34:21