1.问题描述
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
来自 <https://leetcode.com/problems/invert-binary-tree/description/>
2.题目描述
对二叉树进行反转,即便利所有的节点,交换左右孩子。这里使用模仿遍历的方法,进行递归反转。
3.C++代码
//我的c++代码:(beats 98% )
//交换左右孩子
void swap_child (TreeNode *&p)
{
if (p != NULL)
{
TreeNode*tmp;
tmp = p->left;
p->left = p->right;
p->right = tmp;
swap_child(p->left);
swap_child(p->right);
}
}
//反转二叉树
TreeNode* invertTree(TreeNode* root)
{
swap_child(root);
return root;
}
//非递归方法:
//模仿层序遍历
//这个方法我们需要交换树中所有节点的左右子节点。 所以我们创建一个队列来存储左右子节点尚未交换的节点。
//最初,只有根在队列中。 只要队列不为空,就从队列中移除下一个节点,交换其子节点,并将子节点添加到队列中。
//空节点不会添加到队列中。 最终,队列将是空的,并且所有的孩子都会交换,并且我们返回原始的根。
TreeNode* invertTree2(TreeNode* root) {
if (root == NULL)
return NULL;
queue<TreeNode*> que;
que.push(root);
while (!que.empty())
{
TreeNode* p = que.front();
que.pop();
TreeNode* temp = p->left;
p->left = p->right;
p->right = temp;
if (p->left != NULL)
que.push(p->left);
if (p->right != NULL)
que.push(p->right);
}
return root;
}