簡體   English   中英

如何在左右方向遍歷二叉樹?

[英]How to traverse a binary tree in left right direction?

我想要一個在二叉樹中以交替的左,右方向遍歷的解決方案。 級別順序遍歷為“ 1 2 3 4 5 6 7”。 在所需條件下,我的輸出必須為“ 1 2 3 7 6 5 4”。 以下是我編寫的代碼。 這是不正確的。

public void traverseLevel(BinaryTreeNode root) {
    Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
    q.add(root);
    int c = 0;
    while (!q.isEmpty()) {

        root = q.poll();
        System.out.print(root.getData() + " ");
        if (c == 0) {
            c = 1;
            if (root.getLeft() != null) {
                q.add(root.getLeft());
            }
            if (root.getRight() != null) {
                q.add(root.getRight());
            }

        } else {
            c = 0;
            if (root.getRight() != null) {
                q.add(root.getRight());

            }
            if (root.getLeft() != null) {
                q.add(root.getLeft());
            }
        }
    }
}

得到的輸出是“ 1 2 3 5 4 6 7”

我從您的問題中了解到,您想按螺旋順序打印樹。

您可以簡單地使用兩個堆棧

  1. 從左到右打印的第一疊紙。
  2. 從右到左打印的第二個紙疊。

從根節點開始,必須將子級存儲在一個堆棧中。 因此,對於每個迭代,打印節點都位於一個堆棧中。 下一級被推入另一個堆棧中。

我將為您跟蹤實現。 首先,您的隊列包含節點1。

1個

然后,將其子級插入隊列,首先將左側的子級插入隊列,因為c為0。

1 2 3

1然后退出隊列,所以您剩下

2 3

由於您想從現在開始,所以3是理想的起點。 但是,2在您的隊列中排在第一位,因此其子級將被優先推送。

2 3 5 4,然后2退出以形成3 5 4

正是在這一點上3將其子級推入隊列,因為c為0,所以第一個優先。

3 5 4 6 7

我認為您想要做的是擁有一個隊列和一個堆棧,其中隊列包含要打印的項目,並且堆棧接收從隊列中刪除的項目。 然后,您可以彈出堆棧中的每個項目並將其子級推入隊列。

例如,我們從隊列中的1和一個空堆棧開始。 然后,我們從隊列中刪除1,進行打印,然后將其推入堆棧。 然后,我們彈出1並將其子級插入到隊列的最左端。

2 3

接下來,我們打印2並將其放入堆棧中。 與3相同。現在我們的堆棧包含

2 3

然后,我們從堆棧中彈出3,並立即將其子級排入隊列。 然后我們彈出2並對其子節點執行相同操作。 現在我們的隊列包含

7 6 5 4

然后重復該過程,直到您到達所有葉子為止。

還有一個提示:c可以是布爾值而不是數字,因為您只使用0和1作為值。 這樣可以節省空間。 :)

以下方法在C ++中使用STL

struct TreeNode // basic Tree Structure
{
int data;
TreeNode* leftchild;
TreeNode* rightchild;
}
void alternateLeftRight(TreeNode*root)
{
Stack<TreeNode*>currentLevel; // take two stacks 
Stack<TreeNode*>nextLevel;
currentLevel.push(root);
int LeftToRight=0;  // LeftToRight mean we will approach leftchild before rightchild, if LeftToRight=0 , in this case we will approach rightchild first
while(!currentLevel.empty())
{ 

 TreeNode*temp=currentLevel.top();
 cout<<temp->data<<" ";
 currentLevel.pop();
if(LeftToRight)
{
 if(temp->leftchild)nextLevel.push(leftchild);
 if(temp->rightchild)nextLevel.push(rightchild);
}
else
{
  if(temp->leftchild)nextLevel.push(rightchild);
  if(temp->rightchild)nextLevel.push(leftchild);
}

if(currentLevel.empty())
{
swap(currentLevel,nextLevel);
LeftToRight=1-LeftToRight;
}

}

}

暫無
暫無

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

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