【问题标题】:Modify binary tree修改二叉树
【发布时间】:2014-07-20 10:25:13
【问题描述】:

给定一棵二叉树。以这样的方式修改它,以便在修改后您可以仅使用右指针对其进行前序遍历。在修改期间,您可以使用右指针和左指针。

有人建议这种方法吗? 如果我们有 inorder 而不是 preorder 那么我们可以将树修改为 BST 如果我们有后序遍历而不是前序,该怎么做?

【问题讨论】:

  • 为了诚实,这是一个帮助你学习的家庭作业问题吗?
  • 这是一道面试题
  • 你的问题很糟糕。它让任何愿意回答它的人来定义一切。它不符合stackoverflow.com/tour 中的标准这是什么原因?
  • 我只需要一个想法来解决问题,它是如何定义一切的?我没有要求伪代码或正确的代码

标签: c algorithm data-structures tree


【解决方案1】:

这归结为对树进行线性化。前序遍历按照父、左子树、右子树的顺序访问节点。如果我们只想使用右指针来做到这一点,那么左子树必须为空。这样做的想法是重新排列子树。让右指针指向原来的左子树。然后让这个子树的最后一个节点的右指针指向原来的右子树。

这是一个想法:

Node* Linearize(Node* root) // returns the subtree's last node
{
    //if it's a leaf node
    if(root->left == NULL && root->right == NULL)
        return root;

    //if there is no left subtree
    if(root->left == NULL)
        return Linearize(root->right);

    //if there is no right subtree
    if(root->right == NULL)
    {
        root->right = root->left;
        root->left = NULL;
        return Linearize(root->right);
    }

    //both subtrees exist
    Node* left = root->left;
    Node* right = root->right;
    Node* lastOfLeft = Linearize(left);
    root->right = left;
    root->left = NULL;
    lastOfLeft->right = right;
    return Linearize(right);
}

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多