[LeetCode] 866. Smallest Subtree with all the Deepest Nodes

题目描述

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in it’s subtree.

Example 1:

Input: [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation:
avatar
We return the node with value 2, colored in yellow in the diagram.
The nodes colored in blue are the deepest nodes of the tree.
The input “[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]” is a serialization of the given tree.
The output “[2, 7, 4]” is a serialization of the subtree rooted at the node with value 2.
Both the input and output have TreeNode type.

题目描述比较绕,其实实际意思比较直白,要求求出具有最高高度的子树的根节点,或者说是求具有最高高度的非叶子节点。
解决方案可以使用dfs搜索,每次搜索返回当前的根节点以及当前最大深度,如果左右子树深度一样,则返回根节点且深度加一,如果左子树的深度更深,返回左子树的根并且深度加一。相应的,右子树的深度更深,返回右子树的根并且深度加一。

C++ 实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        const pair<int, TreeNode*> res = dfs(root);
        return res.second;
    }
private:
    pair<int, TreeNode*> dfs(TreeNode* root)
    {
        if (!root) return {0, NULL};
        const pair<int, TreeNode*> left = dfs(root->left);
        const pair<int, TreeNode*> right = dfs(root->right);
        if (left.first == right.first) return {left.first + 1, root};
        if (left.first < right.first) return {right.first + 1, right.second};
        return {left.first + 1, left.second};
    }
};

猜你喜欢

转载自blog.csdn.net/carbon06/article/details/80975925
今日推荐