如何反转二叉树

时间:2014-09-21 13:38:19

标签: java binary-tree

让我们假设一棵二叉树

         a
        /     \
       b       c
     /  \     /  \
    d    e    f    g
   / \  / \  / \  / \
   h  i j  k l  m  n  o 

如何扭转它,即

          a
        /     \
       c       b
     /  \     /  \
    f    g    d    e
   / \  / \  / \  / \
   l  m n  o h  i  j  k 

我应该如何跟踪将要反转的二叉树的值。因为当我穿过一棵树时,我会在左半边用左半边交换

2 个答案:

答案 0 :(得分:2)

void reverseLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
        printGivenLevel(root, i);
}

/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        printf("%d ", root->data);
    else if (level > 1)
    {
        printGivenLevel(root->left, level-1);
        printGivenLevel(root->right, level-1);
    }

}

答案 1 :(得分:0)

void mirror(struct node* node) 
{
  if (node==NULL) 
    return;  
  else
  {
    struct node* temp;

    /* do the subtrees */
    mirror(node->left);
    mirror(node->right);

    /* swap the pointers in this node */
    temp        = node->left;
    node->left  = node->right;
    node->right = temp;
  }
}