博文中会简要介绍Leetcode P0226题目分析及解题思路。
“Invert Binary Tree”是一道比较简单的题目,基本思路是利用深度优先搜索,对每层的左子树和右子树进行调换,然后分别进入左右子树重复上述操作。
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
this.invert(root);
return root;
}
private void invert(TreeNode curr) {
if (curr == null)
return;
TreeNode left = curr.left, right = curr.right;curr.left = right;
curr.right = left;
this.invert(left);
this.invert(right);
}
}
以下是C++的题解代码实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
this->_Invert(root);
return root;
}
private:
void _Invert(TreeNode *curr) {
if (!curr)
return;
TreeNode *left = curr->left, *right = curr->right;
this->_Invert(left);
this->_Invert(right);
curr->left = right;
curr->right = left;
}
};