翻转一棵二叉树
样例:
递归&非递归:
#ifndef C175_H
#define C175_H
#include<iostream>
#include<stack>
using namespace std;
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;
if (root->left != NULL || root->right != NULL)
{
TreeNode *node = root->left;
root->left = root->right;
root->right = node;
}
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
};
class Solution2 {
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;
stack<TreeNode*> s;
s.push(root);
while (!s.empty())
{
TreeNode *p = s.top();
s.pop();
TreeNode *node = p->left;
p->left = p->right;
p->right = node;
if (p->left != NULL)
s.push(p->left);
if (p->right != NULL)
s.push(p->right);
}
}
};
#endif