leetcode-剑指58-I-II-OK

// language C with STL(C++)
// 剑指58-I
// https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/submissions/
// 剑指58-II
// https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
	stack<TreeNode*> GetARoad(TreeNode* root,TreeNode* end){
		// 本函数返回值为从root到end的一条路径,装在一个栈里,栈底是root,栈顶是end
		stack<TreeNode*> ans;
		TreeNode* p=root;
		TreeNode* pre = NULL;
		TreeNode* temp;
		while(p || !empty(ans)){
			if(p){
				ans.push(p);
				p= p->left;
			}else{
				p = ans.top();
				if((p->right != NULL) && (p->right !=pre)){
					p = p->right;
					ans.push(p);
					p = p->left;
				}else{
					temp = ans.top();
					if(temp == end)
						return ans;
					else
						ans.pop();
					pre = temp;
					p = NULL;
				}
			}
		}
        return ans;
	}
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    	// 思路:
    	// 利用后续遍历得到从root到p和到q的路径
    	// 然后在在路径里找最近公共祖先
        stack<TreeNode*> RoadP=GetARoad(root,p);
        stack<TreeNode*> RoadQ=GetARoad(root,q);
        int SizeP = RoadP.size();
        int SizeQ = RoadQ.size();
        int min;
        if(SizeP<SizeQ)
        	min = SizeP;
        else
        	min = SizeQ;
        while(SizeP>min){
        	RoadP.pop();
        	SizeP--;
        }
        while(SizeQ>min){
        	RoadQ.pop();
        	SizeQ--;
        }
        while(true){
        	if(RoadP.top() == RoadQ.top())
        		return RoadP.top();
        	else{
        		RoadP.pop();
        		RoadQ.pop();
        	}
        }
        return NULL;
    }
};
posted @ 2021-02-03 15:56  RougeBW  阅读(39)  评论(0编辑  收藏  举报