簡體   English   中英

將鏈表轉換為二叉樹

[英]Converting a linkedlist to binary tree

我有一個包含兩個鏈接的鏈接列表- nextanother假設。 最初,所有another null 現在,我試圖將其轉換為二進制樹next拿着liftChildanother控股rightChild 但是,我想在O(n)和恆定空間中執行此操作。 我已經嘗試了很多。 下面是我的代碼。 我正在通過級別順序遍歷結果樹來驗證結果。 目前,我知道出了什么問題,但不知道如何解決。 這里的錯誤是,在while循環中,我正確地更改了node的鏈接,但這意味着我不能在最后執行node = node.next ,因為nodenext已指向列表中的前面。 因此,我不知道如何遍歷每個節點。 任何提示,幫助表示贊賞。 不是硬件,不是面試問題。 只是嘗試學習數據結構。 因此,這棵樹和所有東西!

public class LlToBt {

  public SpecialNode llToBt(SpecialNode node) {
    SpecialNode temp = node;
    SpecialNode returnNode = node;

    if(node == null)
      return null;
    if(node.next == null)
      return node;

    node = returnNode;
    while(node != null) {
      SpecialNode currentNode = node;

      temp = temp.next;
      if(temp == null) {
        //node.next = null;
        //node.another = null;
        return returnNode;
      }
      node.next = temp;

      temp = temp.next;
      if(temp == null) {
        //node.next = null;
        //node.another = null;
        return returnNode;
      }
      node.another = temp;

      node = currentNode.next;

    }

    return returnNode;
  }
}

如果您正在改變,你會想你穿越它之前穿過的鏈接,那么你需要關閉更改了鏈路之前存儲在不同的變量遍歷的結果。 然后,更改后,您可以使用臨時副本進行遍歷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM