865. Smallest Subtree with all the Deepest Nodes(python+cpp)

寻找最深子树
本文介绍了一种在二叉树中找到包含所有最深层次节点的子树的方法。通过深度优先搜索(DFS)策略,该算法有效地确定了拥有最大深度且包含所有最深节点的树节点。文中提供了Python和C++的实现代码,展示了如何通过递归函数计算节点深度并找出目标子树。

题目:

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

解释:
用dfs做。
python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def subtreeWithAllDeepest(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def depth(root):
            left,right=0,0
            if not root.left and not root.right:
                return root,1
            if root.left and root.right:
                tmp_left,left=depth(root.left)
                tmp_right,right=depth(root.right)
                root_depth=max(left,right)+1
                if left==right:
                    return root,root_depth                                                                  
                elif left>right:
                    return tmp_left,root_depth
                else:
                    return tmp_right,root_depth
            if root.left:
                tmp_left,left=depth(root.left)
                return tmp_left,left+1
            if root.right:
                tmp_right,right=depth(root.right)
                return tmp_right,right+1
        if not root:
            return None
        return depth(root)[0]

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) {
        if (!root)
            return NULL;
        int d=0;
        return depth(root,d);      
    }
    TreeNode* depth(TreeNode* root,int &d)
    {
        if (!root->left && !root->right)
        {
            d=1;
            return root;
        }
        int left_depth=0,right_depth=0;
        if (root->left && root->right)
        {
            TreeNode* tmp_left=depth(root->left,left_depth);
            TreeNode* tmp_right=depth(root->right,right_depth);
            if (left_depth==right_depth)
            {
                d=left_depth+1;
                return root;
            }
            else if(left_depth>right_depth)
            {
                d=left_depth+1;
                return tmp_left;
            }
            else
            {
                d=right_depth+1;
                return tmp_right;
            }
        }
        if(root->left)
        {
            TreeNode* tmp_left=depth(root->left,left_depth);
            d=left_depth+1;
            return tmp_left;
        }
        if(root->right)
        {
            TreeNode* tmp_right=depth(root->right,right_depth);
            d=right_depth+1;
            return tmp_right;
        }
    }
};

总结:
刚开始写得时候先dfs求深度再做外层的dfs,后来发现不需要这么耗时,直接让depth()函数返回两个参数就好。
但是c++如何返回两个参数?深度用引用表示吧。
在论坛上问人,原来c++也有比较方便的split()函数,是boost::split,使用起来非常方便,激动!!!

乐播投屏是一款简单好用、功能强大的专业投屏软件,支持手机投屏电视、手机投电脑、电脑投电视等多种投屏方式。 多端兼容与跨网投屏:支持手机、平板、电脑等多种设备之间的自由组合投屏,且无需连接 WiFi,通过跨屏技术打破网络限制,扫一扫即可投屏。 广泛的应用支持:支持 10000+APP 投屏,包括综合视频、网盘与浏览器、美韩剧、斗鱼、虎牙等直播平台,还能将央视、湖南卫视等各大卫视的直播内容一键投屏。 高清流畅投屏体验:腾讯独家智能音画调校技术,支持 4K 高清画质、240Hz 超高帧率,低延迟不卡顿,能为用户提供更高清、流畅的视觉享受。 会议办公功能强大:拥有全球唯一的 “超级投屏空间”,扫码即投,无需安装。支持多人共享投屏、远程协作批注,PPT、Excel、视频等文件都能流畅展示,还具备企业级安全加密,保障会议资料不泄露。 多人互动功能:支持多人投屏,邀请好友加入投屏互动,远程也可加入。同时具备一屏多显、语音互动功能,支持多人连麦,实时语音交流。 文件支持全面:支持 PPT、PDF、Word、Excel 等办公文件,以及视频、图片等多种类型文件的投屏,还支持网盘直投,无需下载和转格式。 特色功能丰富:投屏时可同步录制投屏画面,部分版本还支持通过触控屏或电视端外接鼠标反控电脑,以及在投屏过程中用画笔实时标注等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值