二叉樹中最重要的操作莫過於遍歷,即按照某一順序訪問樹中的所有結點。
以下這三種遍歷都有遞迴和迴圈兩種實現方法,每一種遍歷的遞迴都要比迴圈實現簡潔地多。
前序遍歷首先訪問根結點然後遍歷左子樹,最後遍歷右子樹。在遍歷左、右子樹時,仍然先訪問根結點,然後遍歷左子樹,最後遍歷右子樹。
遞迴實現:
迴圈實現:void preorder(btnode *b)
}
中序遍歷首先遍歷左子樹,然後訪問根結點,最後遍歷右子樹。在遍歷左、右子樹時,仍然先遍歷左子樹,再訪問根結點,最後遍歷右子樹。void preorder(btnode *b)
if(p->lchild!=null)//左孩子入棧
}printf("\n");
} }
遞迴實現:
迴圈實現:void inorder(btnode *b)
}
後序遍歷首先遍歷左子樹,然後訪問右子樹,最後遍歷根結點。在遍歷左,右子樹時,仍然先遍歷左子樹,再遍歷右子樹,最後訪問根結點。void inorder(btnode *b)
if(top>-1)
}printf("\n");
} }
遞迴實現:
迴圈實現:void postorder(btnode *b)
}
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不包含重複的數字。例如:輸入前序遍歷和中序遍歷。void postorder(btnode *b)
p=null; //p指向當前結點的前乙個已訪問結點
flag=1;
while(top!=-1&&flag)
else
}}while(top!=-1);
printf("\n");
}
binarytreenode* construct(int* preorder,int* inorder,int length)
binarytreenode* constructcore(int* startpreorder,int* endpreorder;int* startinorder,int* endinorder)
//中序遍歷中找到根結點的值
int* rootinorder=startinorder;
while(rootinorder<=endinorder && *rootinorder!=rootvalue)
++rootinorder;
if(rootinorder==endinorder && *rootinorder!=rootvalue)
throw
std::exception("invalid input.");
int leftlength=rootinorder-startinorder;
int* leftpreorderend=startpreorder+leftlength;
if(leftlength>0)
if(leftlength//構建右子樹
root->m_pright=constructcore(leftpreorderend+1,endpreorder,rootinorder+1,endinorder);
}return root;
}
面試題6 重建二叉樹
面試題6 題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,重建出該二叉樹。不包含重複數字。前序遍歷的第乙個結果就是根節點,中序遍歷中根節點前面的節點就是左子樹,後面的節點就是右子樹。然後遞迴的構建左右子樹。binarytreenode constructbinarynode int startpreo...
面試題6 重建二叉樹
templatestruct binarytreenode 對比二叉樹的圖形和其兩個遍歷序列來看,可以發現在前序遍歷序列中第乙個數字總是二叉樹的根節點的值,然後在中序遍歷序列中找到該值,它的前面就是它左子樹上節點值的集合,後面就是它右子樹上節點值的集合。由此就可以遞迴地在這兩個集合中建立二叉樹。bi...
面試題6 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二節樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。param preorder 前序遍歷 param inorder 中序遍歷 return 樹的根結點 public static binarytreenode construct int...