翻转二叉树-LintCode

来源:互联网 发布:淘宝店铺支付宝限额 编辑:程序博客网 时间:2024/06/05 20:53

翻转一棵二叉树
样例:
这里写图片描述
递归&非递归:

#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
原创粉丝点击