Given the root
of a binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
0
. if the depth of a node is d
, the depth of each of its children is d + 1
.S
of nodes, is the node A
with the largest depth such that every node in S
is in the subtree with root A
.Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
Example 2:
Input: root = [1] Output: [1] Explanation: The root is the deepest node in the tree, and it's the lca of itself.
Example 3:
Input: root = [0,1,3,null,2] Output: [2] Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.
Constraints:
[1, 1000]
.0 <= Node.val <= 1000
题目:给定一个二叉树,找 最深两个叶子的最低公共祖先。
思路:需要有一个全局变量记录整个子树的最深深度,此变量再遍历时是实时更新的。同时需要局部变量记录以当前子节点为根的子树所包含叶子的深度。如果当前节点左子树与右子树深度相同,且同为最深深度,则该子节点即为我们所求。因此,单次遍历,通过递归所隐含的栈结构来记录从上往下遍历树时的深度,从下往上时回传当前节点子辈的最深深度。判断当前节点左右子辈的最深深度是否相等,且是否等于整棵树的最深深度。如是,则更新结果。
代码:
/**
* 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 {
private:
int depth = 0;
TreeNode* res = NULL;
public:
int helper(TreeNode* node, int level){
if(!node) return level;
level++;
depth = max(level, depth);
int l = helper(node->left, level);
int r = helper(node->right, level);
if(l == r && l == depth) res = node;
return max(l, r);
}
TreeNode* lcaDeepestLeaves(TreeNode* root) {
helper(root, 0);
return res;
}
};