题目:1123. 最深叶节点的最近公共祖先
思路:深度优先搜索dfs,时间复杂度0(n)。这道题的进阶版思路:(LeetCode)236. 二叉树的最近公共祖先(深度优先搜索dfs 、二叉树)
只有当左子树和右子树的最深长度相等时,才会发生找最近公共祖先的情况。而该祖先不一定是最深的叶子节点的祖先,所以维护最大的深度mx_depth。细节看注释
C++版本:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int mx_depth=-1;
TreeNode * target=nullptr;
int dfs(TreeNode * root,int depth){
//为空
if(root == nullptr){
//维护最大的深度mx_depth
mx_depth=max(mx_depth,depth);
return depth;
}
//左子树的最大深度
int left=dfs(root->left,depth+1);
//右子树的最大深度
int right=dfs(root->right,depth+1);
//当左子树和右子树的最深长度相等,且为最大深度时,找的最近公共祖先才会是最优值
if(left==right && left>=mx_depth){
target = root;
}
//返回当前子树的最大深度
return max(left,right);
}
TreeNode* lcaDeepestLeaves(TreeNode* root) {
dfs(root,0);
cout<<mx_depth;
return target;
}
};
JAVA版本:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode target=null;
int mx_depth=0;
int dfs(TreeNode root,int depth){
if(root ==null){
mx_depth=Math.max(mx_depth,depth);
return depth;
}
int left = dfs(root.left,depth+1);
int right = dfs(root.right,depth+1);
if(left==right && left ==mx_depth){
target=root;
}
return Math.max(left,right);
}
public TreeNode lcaDeepestLeaves(TreeNode root) {
dfs(root,0);
return target;
}
}
Go版本:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lcaDeepestLeaves(root *TreeNode) *TreeNode {
var target *TreeNode =nil
mx_depth :=0
var dfs func(*TreeNode,int) int
dfs=func(root *TreeNode,depth int) int {
if root == nil {
mx_depth=max(mx_depth,depth)
return depth
}
left := dfs(root.Left,depth+1)
right := dfs(root.Right,depth+1)
if left==right && left==mx_depth {
target =root
}
return max(left,right)
}
dfs(root,0)
return target
}