二叉树的镜象

时间:2010-12-06 12:12:19

标签: algorithm data-structures

假设有一棵树:

             1
            / \
           2   3
              / \
             4   5

然后镜像将是:

              1
             / \
            3   2
           / \
          5   4

假设节点具有以下结构:

struct node{
      node left;
      node right;
      int value;
}

有人可以为此建议算法吗?

13 个答案:

答案 0 :(得分:35)

听起来像是家庭作业。

看起来很容易。编写一个递归例程,深度优先访问每个节点,并构建左右反转的镜像树。

struct node *mirror(struct node *here) {

  if (here == NULL)
     return NULL;
  else {

    struct node *newNode = malloc (sizeof(struct node));

    newNode->value = here->value;
    newNode->left = mirror(here->right);
    newNode->right = mirror(here->left);

    return newNode;
  }
}

这将返回一个新树 - 其他一些答案就是这样做的。取决于你的任务要求你做什么:)

答案 1 :(得分:26)

void swap_node(node n) {
  if(n != null) {
    node tmp = n.left;
    n.left = n.right;
    n.right = tmp;

    swap_node(n.left);
    swap_node(n.right);
  }
}

swap_node(root);

答案 2 :(得分:10)

Banal解决方案:

for each node in tree
    exchange leftchild with rightchild.

答案 3 :(得分:5)

JAVA中的递归和迭代方法: 1)递归:

    public static TreeNode mirrorBinaryTree(TreeNode root){

    if(root == null || (root.left == null && root.right == null))
        return root;

    TreeNode temp = root.left;
    root.left = root.right;
    root.right = temp;

    mirrorBinaryTree(root.left);
    mirrorBinaryTree(root.right);


    return root;

}

2)迭代:

public static TreeNode mirrorBinaryTreeIterative(TreeNode root){
    if(root == null || (root.left == null && root.right == null))
        return root;

    TreeNode parent = root;
    Stack<TreeNode> treeStack = new Stack<TreeNode>();
    treeStack.push(root);

    while(!treeStack.empty()){
        parent = treeStack.pop();

        TreeNode temp = parent.right;
        parent.right = parent.left;
        parent.left = temp;

        if(parent.right != null)
            treeStack.push(parent.right);
        if(parent.left != null)
            treeStack.push(parent.left);
    }
    return root;
}

答案 4 :(得分:3)

void mirror(struct node* node)  
{
   if (node==NULL)
   {
      return;
   }
   else 
   {
      struct node* temp;
      mirror(node->left);
      mirror(node->right);
      temp = node->left;
      node->left = node->right;
      node->right = temp;
    }
}

答案 5 :(得分:3)

迭代解决方案:

public void mirrorIterative() {
    Queue<TreeNode> nodeQ = new LinkedList<TreeNode>();
    nodeQ.add(root);
    while(!nodeQ.isEmpty()) {
        TreeNode node = nodeQ.remove();
        if(node.leftChild == null && node.rightChild == null)
            continue;
        if(node.leftChild != null && node.rightChild != null) {
            TreeNode temp = node.leftChild;
            node.leftChild = node.rightChild;
            node.rightChild = temp;
            nodeQ.add(node.leftChild);
            nodeQ.add(node.rightChild);
        }
        else if(node.leftChild == null) {
            node.leftChild = node.rightChild;
            node.rightChild = null;
            nodeQ.add(node.leftChild);
        } else {
            node.rightChild = node.leftChild;
            node.leftChild = null;
            nodeQ.add(node.rightChild);
        }
    }
}

答案 6 :(得分:2)

void mirror(node<t> *& root2,node<t> * root)
{
    if(root==NULL)
    {
        root2=NULL;
    }
    else {
        root2=new node<t>;
        root2->data=root->data;
        root2->left=NULL;
        root2->right=NULL;
        mirror(root2->left,root->right);
        mirror(root2->right,root->left);
    }
}

答案 7 :(得分:1)

TreeNode * mirror(TreeNode *node){
  if(node==NULL){
    return NULL;
  }else{
    TreeNode *temp=node->left;
    node->left=mirror(node->right);
    node->right=mirror(temp);
    return node;
  }
}

答案 8 :(得分:0)

这是我的功能。建议是否有更好的解决方案:

void mirrorimage(struct node *p)
{
    struct node *q;
    if(p!=NULL)
    {
        q=swaptrs(&p);
        p=q;
        mirrorimage(p->left);
        mirrorimage(p->right);
    }
}

struct node* swaptrs(struct node **p)
{
    struct node *temp;
    temp=(*p)->left;
    (*p)->left=(*p)->right;
    (*p)->right=temp;
    return (*p);
}

答案 9 :(得分:0)

递归Java代码

public class TreeMirrorImageCreator {

public static Node createMirrorImage(Node originalNode,Node mirroredNode){

    mirroredNode.setValue(originalNode.getValue());

    if(originalNode.getLeft() != null){
        mirroredNode.setLeft(createMirrorImage(originalNode.getRight(),new Node(0)));
    }

    if(originalNode.getRight() != null){
        mirroredNode.setRight(createMirrorImage(originalNode.getLeft(), new Node(0)));
    }

    return mirroredNode;

}
}

答案 10 :(得分:0)

struct node *MirrorOfBinaryTree( struct node *root)
{ struct node *temp;
if(root)
{
MirrorOfBinaryTree(root->left);
MirrorOfBinaryTree(root->right);
/*swap the pointers in this node*/
temp=root->right;
root->right=root->left;;
root->left=temp;
}
return root;
}

时间复杂度:O(n) 空间复杂度:O(n)

答案 11 :(得分:0)

嗯,这个问题得到了很多答案。我发布的迭代版本很容易理解。这使用级别顺序遍历。

Call Text_bold(Application.Union(Range("B5:C5"), Range("B6:C6")))

答案 12 :(得分:0)

这是在Python中使用队列的非递归方法。 Queue类可以这样初始化:

String s1="aeiou";
String s2="This is a test string which could be any text";

s2 = string.Concat(s2.Where(c => !s1.Contains(c)));
Console.WriteLine(s2);

代表节点的类:

class Queue(object):
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.insert(0, item)

    def dequeue(self):
        if not self.is_empty():
            return self.items.pop()

    def is_empty(self):
        return len(self.items) == 0

    def peek(self):
        if not self.is_empty():
            return self.items[-1]

    def __len__(self):
        return self.size()

    def size(self):
        return len(self.items)

这是完成主要任务的方法:

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.val = data