We consider the problem of optimal energy allocation and lifetime maximization in heterogeneous wireless sensor networks. We construct a probabilistic model for heterogeneous wireless sensor networks where sensors can have different sensing range, different transmission range, different energy consumption for data sensing, and different energy consumption for data transmission, and the stream of data sensed and transmitted from a sensor and the stream of data relayed by a sensor to a base station are all treated as Poisson streams. We derive the probability distribution and the expectation of the number of data transmissions during the lifetime of each sensor and the probability distribution and the expectation of the lifetime of each sensor. In all these analysis, energy consumption of data sensing and data transmission and data relay are all taken into consideration. We develop an algorithm to find an optimal initial energy allocation to the sensors such that the network lifetime in the sense of the identical expected sensor lifetime is maximized. We show how to deal with a large amount of energy budget that may cause excessive computational time by developing accurate closed form approximate expressions of sensor lifetime and network lifetime and optimal initial energy allocation. We derive the expected number of working sensors at any time. Based on such results, we can find the latest time such that the expected number of sensors that are still functioning up to that time is above certain threshold.