topic:
Sword finger Offer 68 - II. The recent public ancestor of the binary tree.md
Thought:
Termination condition:
Dangyan leaves,Return directly null ;
when root equal p,qp, qp,q ,Return directly root ;
Recursive work:
Open the recursive Zuozi node,Return to value left ;
Open recursive right -child node,Return to value right ;
return value: according to left and right ,Can be expanded in four situations;
- when left and right At the same time as an empty :illustrate root Left / Nothing in the right tree is not included p,q,return null ;
- when left and right Not empty at the same time :illustrate p,q Be included in root of Heterochrome (Respectively Left / Right -handed tree),therefore root For the recent public ancestors,return root ;
- when left Is empty ,right 不Is empty :p,q Nothing root Left子树middle,直接return right 。Specific can be divided into two cases:
- p,q One of them is root of Right -handed tree middle,at this time right direction p(Assume p );
- p,q Both nodes are there root of Right -handed tree middle,at this timeof right direction Public ancestor node recently ;
- when left 不Is empty , right Is empty :Situation 3. Same;
Code:
1 | class Solution: |