题解 | #二叉树的镜像#

二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <any>
#include <limits>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        // write code here
        //使用非递归的方法镜像翻转二叉树,实际就是前序遍历时,交换每个结点左右子树
        TreeNode* bt=pRoot;
        stack<TreeNode*> s;
        
        while(!s.empty()||bt!=nullptr)
        {
            while(bt!=nullptr)
            {
                swap(bt->left, bt->right);

                s.push(bt);
                bt=bt->left;
            }   

            if(!s.empty())
            {
                bt=s.top();
                s.pop();
                bt=bt->right;
            }
        }

        return pRoot;
    }
};

全部评论

相关推荐

点赞 评论 收藏
转发
2 收藏 评论
分享
牛客网
牛客企业服务