2021-10-11 ! LeetCode226. 翻转二叉树 的前中后层序遍历写法

还是遍历框架的应用

//! 二叉树的翻转:本质就是二叉树的遍历的应用
//! 以任意形式遍历二叉树的每一个结点,访问每一个结点的同时调换其左右子树
//! 中序遍历额外注意一下调换后的参数问题
Node *BinarySearchTreesZH::invertTreePreOrder(Node *node)
{
    if (node == nullptr)
    {
        return node;
    }
    Node *tmp = node->left;
    node->left = node->right;
    node->right = tmp;
    invertTreePreOrder(node->left);  //!这里遍历的主要目的是遍历过程中的副作用。即翻转
    invertTreePreOrder(node->right); //! 所以这里不return,要灵活运用遍历框架
    return node;
}
Node *BinarySearchTreesZH::invertTreeInOrder(Node *node)
{
    if (node == nullptr)
    {
        return node;
    }
    invertTreeInOrder(node->left);
    Node *tmp = node->left;
    node->left = node->right;
    node->right = tmp;
    //! 中序遍历的特殊点:由于调换了左右子树,所以第二个递归参数应该是现在的左子树才是原来的右子树
    invertTreeInOrder(node->left);
    return node;
}
Node *BinarySearchTreesZH::invertTreePostOrder(Node *node)
{
    if (node == nullptr)
    {
        return node;
    }
    invertTreePostOrder(node->left);
    invertTreePostOrder(node->right);
    Node *tmp = node->left;
    node->left = node->right;
    node->right = tmp;
    return node;
}
Node *BinarySearchTreesZH::invertTreeLeverOrder(Node *node)
{
    if (node == nullptr)
    {
        return node;
    }
    queue<Node *> list;
    list.push(node);
    while (list.size() != 0)
    {
        Node *front = list.front();
        list.pop();
        Node *tmp = front->left;
        front->left = front->right;
        front->right = tmp;
        if (front->left != nullptr)
        {
            list.push(front->left);
        }
        if (front->right != nullptr)
        {
            list.push(front->right);
        }
    }
    return node;
}
上一篇:队列的顺序表现和实现 02


下一篇:数据结构笔记——队列