标签:type data- desc c代码 父节点 this tree btn 优先
原题网址:https://www.lintcode.com/problem/invert-binary-tree/description
翻转一棵二叉树
1 1
/ \ / 2 3 => 3 2
/ 4 4
递归固然可行,能否写个非递归的?
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode * root) {
// write your code here
if (root==NULL)
{
return ;
}
invertBinaryTree(root->left);
invertBinaryTree(root->right);
TreeNode *temp=root->right;
root->right=root->left;
root->left=temp;
}
};
非递归:广度优先搜索。从根开始一层层遍历,交换结点的左右孩子。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode * root) {
// write your code here
if (root==NULL)
{
return ;
}
queue<TreeNode *> tmp;
tmp.push(root);
while(!tmp.empty())
{
TreeNode *p=tmp.front();
tmp.pop();
swap(p->left,p->right);
if (p->left!=NULL)
{
tmp.push(p->left);
}
if (p->right!=NULL)
{
tmp.push(p->right);
}
}
}
};
标签:type data- desc c代码 父节点 this tree btn 优先
原文地址:https://www.cnblogs.com/Tang-tangt/p/9175104.html