LeetCode 1123. 最深叶节点的最近公共祖先(递归比较子树高度)

1. 题目

给你一个有根节点的二叉树,找到它最深叶节点的最近公共祖先。

回想一下:

  • 叶节点 是二叉树中没有子节点的节点
  • 树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
  • 如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值
示例 1:
输入:root = [1,2,3]
输出:[1,2,3]

示例 2:
输入:root = [1,2,3,4]
输出:[4]

示例 3:
输入:root = [1,2,3,4,5]
输出:[2,4,5]
 
提示:
给你的树中将有 11000 个节点。
树中每个节点的值都在 11000 之间。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 求左右子树的高度,相等返回 root
  • 不等,递归判断高的子树一侧
class Solution {
public:
    TreeNode* lcaDeepestLeaves(TreeNode* root) {
    	if(!root)
    		return NULL;
    	int hl = height(root->left);
    	int hr = height(root->right);
    	if(hl == hr)
    		return root;
    	else if(hl < hr)
    		return lcaDeepestLeaves(root->right);
		else
    		return lcaDeepestLeaves(root->left);
    }

    int height(TreeNode* root)
    {
    	if(!root)
    		return 0;
    	return 1+max(height(root->left),height(root->right));
    }
};
发布了853 篇原创文章 · 获赞 2305 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105547346