112 - Tree Summing

 Tree Summing 

Background

LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees.

This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property.

The Problem

Given a binary tree of integers, you are to write a program that determines whether there exists a root-to-leaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18.

picture25

Binary trees are represented in the input file as LISP S-expressions having the following form.

 
empty tree 		 ::= 		 ()

tree ::= empty tree tex2html_wrap_inline118 (integer tree tree)

The tree diagrammed above is represented by the expression (5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )

Note that with this formulation all leaves of a tree are of the form (integer () () )

Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively.

The Input

The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression as described above. All binary tree S-expressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by end-of-file.

The Output

There should be one line of output for each test case (integer/tree pair) in the input file. For each pairI,T (I represents the integer, T represents the tree) the output is the string yes if there is a root-to-leaf path in T whose sum is I and no if there is no path in T whose sum is I.

Sample Input

22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3 
     (2 (4 () () )
        (8 () () ) )
     (1 (6 () () )
        (4 () () ) ) )
5 ()

Sample Output

yes
no
yes
no

题意:一颗二叉树,用()表示一颗空树,(数字,()())来表示只有根节点的树,依次类推来表示这棵二叉树。

然后给你一个数,问是否能够从根节点开始到叶子的路径上的所有数字相加等于该数。


想法:这几天刚刚接触树。有点被搞得云里雾里的。

所以这道题其实是不需要建树的,不过我还是建立了树。也算是再巩固巩固。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
struct tree
{
    int data;
    int sum;
    tree* lchild;
    tree* rchild;
};//树的结点,用data来记录结点内容,用sum来记录从根节点到该节点的总数
tree* newnode()
{
    tree* u=(tree*) malloc (sizeof(tree));
    u->lchild=u->rchild=NULL;
    u->data=u->sum=0;
    return u;
}//建立一个新的结点
int n;
bool flag=false;
tree* input(tree * u, int t)
{
    char ch;
    int v;
    cin>>ch;//用来接收(
    u=newnode();
    if (!(cin>>v)==0)
    {
        u->data=v;
        u->sum=t+v;
        u->lchild=input(u->lchild,u->sum);
        u->rchild=input(u->rchild,u->sum);
        cin>>ch;//接收)
    }
    else
    {
        cin.clear();//这个函数能够将cin的错误信息清空
        cin>>ch;
        u=NULL;
    }
    if (u!=NULL)//判断是否满足条件
    {
        if (u->sum==n && !u->lchild && !u->rchild) flag=true;
    }
    return u;
}
void Preorder(tree *u)//这个前序遍历可以无视
{
    if (u!=NULL)
    {
        cout<<u->data<<" "<<u->sum<<"! ";
        Preorder(u->lchild);
        Preorder(u->rchild);
    }
}
int main ()
{
    int i,j,t;
    while(cin>>n)
    {
        flag=false;
        front=0;
        tree *root=newnode();
        root=input(root,0);
        if (flag) cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
    return 0;
}


霍夫曼编码(Huffman Coding)是一种基于概率的无损数据压缩算法,常用于文本编码。在MATLAB中实现霍夫曼编码,你可以按照以下步骤进行: 1. 创建一个函数,接受输入参数`P`,这是一个包含信源待符号及其对应概率的向量或矩阵。 2. 对概率进行排序:从最小到最大。 3. 初始化树:创建一个空的二叉树结构,如元组列表或自定义结构体。 4. 建立霍夫曼树:使用贪心策略,每次合并频率最低的两个节点,形成新的节点,直到只剩下一个叶子节点,这个就是根节点。可以递归地执行此过程。 5. 编码:遍历霍夫曼树,给每个叶节点分配一个编码。从根节点开始,如果左分支对应的是当前的概率值,则编码为0,否则编码为1,然后向下一层移动。记录下每个符号对应的编码。 6. 返回编码:将编码结果存储在一个映射表或者数组中,键是原始符号,值是对应的Huffman码。 以下是简化的MATLAB代码实现示例: ```matlab function huffmann_code = huffman_encoding(P) % 检查输入是否合法 if nargin < 2 || ~isnumeric(P) || any(P <= 0) || sum(P) ~= 1 error('Invalid input. Probability distribution P must be a non-negative vector summing to 1.'); end % 对概率降序排列 [sorted_prob, idx] = sort(P, 'descend'); % 初始化霍夫曼树 tree = cell(1, length(sorted_prob)); for i = 1:length(idx) tree{i} = struct('left', [], 'right', [], 'prob', sorted_prob(i)); end % 构建霍夫曼树 while length(tree) > 1 % 找到频率最低的两个节点 [min_prob, min_idx] = min([tree{:}.prob]); left = tree{min_idx}.left; right = tree{min_idx}.right; % 合并节点 new_node = struct('left', left, 'right', right, 'prob', left.prob + right.prob); for i = 1:length(tree) if tree{i} == left || tree{i} == right tree{i} = new_node; break; end end tree = tree(~ismember(tree, [left, right])); end % 遍历霍夫曼树获取编码 huffmann_code = cellfun(@(x) dec2bin(x), [0:length(tree)-1], 'UniformOutput', false); % 使用霍夫曼树的索引作为编码 huffmann_code = cellfun(@(x, p) char(x) * num2str(p*8), huffmann_code', sorted_prob', 'Un', true); end ``` 要调用该函数,传入信源待号的概率分布: ```matlab % 示例概率分布 P = [0.1, 0.2, 0.3, 0.4]; % 假设有四个符号和对应概率 % 运行编码函数 huffmann_codes = huffman_encoding(P); % 查看编码结果 disp(huffmann_codes); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值