码迷,mamicode.com
首页 > 其他好文 > 详细

刷题236. Lowest Common Ancestor of a Binary Tree

时间:2020-04-05 09:24:53      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:tor   递归   ret   一个   ==   方法   sage   code   解答   

一、题目说明

题目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.

三、优化措施

其他方法,暂时想不起来。

刷题236. Lowest Common Ancestor of a Binary Tree

标签:tor   递归   ret   一个   ==   方法   sage   code   解答   

原文地址:https://www.cnblogs.com/siweihz/p/12288490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!