(剑指offer) 重建二叉树 旋转数组的最小数字

根据前序遍历和后序遍历重建二叉树

            

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
	TreeNode * function(const vector<int>& pre, int s1, int e1, const vector<int>& vin, int s2, int e2) {
		if (s1 == e1)
			return nullptr;
		TreeNode *root = new TreeNode(pre[s1]);
		int i = s2;
		while (i != e2) {
			if (vin[i++] == pre[s1])
				break;
		}
		root->left = function(pre, s1 + 1, s1 + i - s2, vin, s2, i - 1);
		root->right = function(pre, s1 + i - s2 , e1, vin, i, e2);
		return root;
	}

	TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
		int size1 = pre.size(), size2 = vin.size();
		return function(pre, 0, size1, vin, 0, size2);
	}
};

旋转数组的最小数字

            这一题要注意等于的情况。当因为首位元素可能相等,当中间元素和端点元素相等时我们是判断不了最小数字在mid前段还是mid后段。

class Solution {
public:
	int minNumberInRotateArray(vector<int> rotateArray) {
		if (rotateArray.empty())
			return 0;
		int left = 0, right = rotateArray.size() - 1;
		while (left < right) {
			int mid = left + (right - left) / 2;
			if (rotateArray[mid] > rotateArray[right])
				left = mid + 1;
			else if (rotateArray[mid] < rotateArray[right])
				right = mid;
			else
				++left;
		}
		return rotateArray[left];
	}
};


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页