[Tree]樹與先序遍歷

如果我們有一個先序遍歷的數組或者一個鏈表,以它們來建立一棵樹,但是又無法很好的劃分左右子樹,可以用下面的框架。

	TreeNode *buildTree(vector<int> &preorder, int &cur, int min, int max)
	{
		if(cur >= preorder.size()) return NULL;
		TreeNode *root = NULL;
		if(preorder[cur] >= min && preorder[cur] <= max)
		{
			root = new TreeNode(preorder[cur]);
			cur++;
			root->left = buildTree(preorder, cur, min, root->val);
			root->right = buildTree(preorder, cur, root->val, max);
		}
		return root;
	}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章