刷題236. Lowest Common Ancestor of a Binary Tree

一、題目說明

題目236. Lowest Common Ancestor of a Binary Tree,在一個二叉樹中找兩個節點的最近公共祖先。難度是Medium!

二、我的解答

這個用二叉樹的遞歸遍歷,稍加改造即可:

class Solution{
	public:
		TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode*p,TreeNode*q){
			if(root == NULL) return root;
			if(root == p || root==q) return root;
			TreeNode* left,*right;
			left = lowestCommonAncestor(root->left,p,q);
			right = lowestCommonAncestor(root->right,p,q);
			if(left !=NULL && right!=NULL){
				return root;
			}else if(left != NULL){
				return left;
			}else if(right != NULL){
				return right;
			}else{
				return NULL;
			}
		}
};

性能如下:

Runtime: 16 ms, faster than 94.88% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
Memory Usage: 16.7 MB, less than 87.27% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.

三、優化措施

其他方法,暫時想不起來。

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