二叉树中,如果一个节点是其父节点的唯一子节点,则称这样的节点为 “独生节点” 。 二叉树的根节点不会是独生节点,因为它没有父节点。
给定一棵二叉树的根节点 root ,返回树中 所有的独生节点的值所构成的数组 。 数组的顺序 不限 。
示例 1:
输入:root = [1,2,3,null,4]
输出:[4]
解释:浅蓝色的节点是唯一的独生节点。
节点 1 是根节点,不是独生的。
节点 2 和 3 有共同的父节点,所以它们都不是独生的。
提示:
tree 中节点个数的取值范围是 [1, 1000]。
每个节点的值的取值范围是 [1, 10^6]。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-all-the-lonely-nodes 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
vector<int> ans;
public:
vector<int> getLonelyNodes(TreeNode* root) {
if(!root)
return {};
if(!root->left && root->right)
ans.push_back(root->right->val);
if(root->left && !root->right)
ans.push_back(root->left->val);
getLonelyNodes(root->left);
getLonelyNodes(root->right);
return ans;
}
};
48 ms 43.5 MB
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有