LeetCode: 866. Smallest Subtree with all the Deepest Nodes

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:
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.

这里写图片描述

Note:

The number of nodes in the tree will be between 1 and 500.
The values of each node are unique.

解题思路 —— 递归求解

  1. 如果 rootnullptr,则直接返回 nullptr;
  2. 如果 root 的左子树的深度等于 root 的右子树的深度,则返回 root;
  3. 如果 root 的左子树的深度大于 root 的右子树的深度,则返回 root 的左子树的 mallest Subtree with all the Deepest Nodes;
  4. 否则,root 的左子树的深度小于root 的右子树的深度,则返回 root 的右子树的 mallest Subtree with all the Deepest Nodes;

AC 代码

/**
 * 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
{
    // 获取二叉树 root 的 Smallest Subtree with all the Deepest Nodes
    // 参数:TreeNode* root, 待处理的二叉树
    //      TreeNode*& deepestNode, 二叉树 root 的 Smallest Subtree with all the Deepest Nodes
    // 返回: 二叉树 root 的  Deepest Nodes 的深度
    int subtreeWithAllDeepestRef(TreeNode* root, TreeNode*& deepestNode)
    {
        if(root == nullptr)
        {
            deepestNode = nullptr;
            return 0;
        }

        // 分别处理左右子树
        TreeNode* leftDeepest = nullptr, *rightDeepest = nullptr;
        int leftDepth = subtreeWithAllDeepestRef(root->left, leftDeepest);
        int rightDepth = subtreeWithAllDeepestRef(root->right, rightDeepest);

        if(leftDepth == rightDepth) // 1. 左右子树的深度相等,则返回当前 root 节点
        {
            deepestNode = root;
            return leftDepth+1;
        }
        else if(leftDepth > rightDepth) // 2. 左子树更深,则返回左子树的 deepestNode
        {
            deepestNode = leftDeepest;
            return leftDepth+1;
        }
        else // 3. 否则,右子树更深,返回右子树的 deepestNode
        {
            deepestNode = rightDeepest;
            return rightDepth+1;
        }

    }
public:
    TreeNode* subtreeWithAllDeepest(TreeNode* root) 
    {
        TreeNode* deepestNode = nullptr;
        subtreeWithAllDeepestRef(root, deepestNode);
        return deepestNode;
    }
};

猜你喜欢

转载自blog.csdn.net/yanglingwell/article/details/80960377