UVA 112(二叉树、DFS)

I - Tree Summing
Crawling failed
Appoint description: 

Description

Download as PDF


 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 treetex2html_wrap_inline118 (integer treetree)

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 pair I,T (I represents the integer, Trepresents 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<stdio.h>
#include<cstring>
struct tree
{
    int date;
    tree *l,*r;
    tree()
    {
        date=0;
        l=r=NULL;
    }
};
tree* built()
{
   tree *now=new tree;
   now->date=0;
   now->l=now->r=NULL;
   int cnt=0,flag=0;
   char ch;
   while((ch=getchar())!=EOF)
   {
       if(ch>='0'&&ch<='9')now->date=now->date*10+ch-'0';
       else if(ch=='(')
       {
           if(!cnt)now->l=built();
           else if(cnt==1)now->r=built();
           cnt++;
       }
       else if(ch=='-')flag=1;
       else if(ch==')')break;
   }
   if(flag)now->date=-now->date;
   if(!cnt&&!now->date){delete now;now=NULL;}//½Úµã²»´æÔÚ
   return now;
}
void del(tree *p)
{
    if(!p)return;
    if(p->l)del(p->l);
    if(p->r)del(p->r);
    delete p;
    p=NULL;
}
int dfs(tree *Root,int sum,int aim)
{
    if(Root==NULL)return 0;
    if(Root->l==NULL&&Root->r==NULL)
    {
        if(sum+Root->date==aim)return 1;
        return 0;
    }
    if(dfs(Root->l,sum+Root->date,aim)+dfs(Root->r,sum+Root->date,aim))return 1;
    return 0;
}
int main()
{
    int n;
    char ch;
    tree *root;
    //freopen("in.txt","r",stdin);
    while(~scanf("%d",&n))
    {
        root=NULL;
        while((ch=getchar())!=EOF)
        {
            if(ch=='('){root=built();break;}
        }
        if(dfs(root,0,n))printf("yes\n");
        else printf("no\n");
        del(root);
    }
    return 0;
}



在Java中,二叉树的深度优先搜索(DFS)是一种遍历二叉树的方法。DFS有三种常见的方式:前序遍历、中序遍历和后序遍历。 1. 前序遍历(Preorder Traversal):首先访问根节点,然后递归地遍历左子树,最后递归地遍历右子树。 2. 中序遍历(Inorder Traversal):首先递归地遍历左子树,然后访问根节点,最后递归地遍历右子树。 3. 后序遍历(Postorder Traversal):首先递归地遍历左子树,然后递归地遍历右子树,最后访问根节点。 下面是一个示例代码,展示了如何使用递归实现二叉树DFS: ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } public class BinaryTreeDFS { public void preorderTraversal(TreeNode root) { if (root == null) { return; } System.out.print(root.val + " "); preorderTraversal(root.left); preorderTraversal(root.right); } public void inorderTraversal(TreeNode root) { if (root == null) { return; } inorderTraversal(root.left); System.out.print(root.val + " "); inorderTraversal(root.right); } public void postorderTraversal(TreeNode root) { if (root == null) { return; } postorderTraversal(root.left); postorderTraversal(root.right); System.out.print(root.val + " "); } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); BinaryTreeDFS binaryTreeDFS = new BinaryTreeDFS(); System.out.println("Preorder Traversal:"); binaryTreeDFS.preorderTraversal(root); System.out.println("\nInorder Traversal:"); binaryTreeDFS.inorderTraversal(root); System.out.println("\nPostorder Traversal:"); binaryTreeDFS.postorderTraversal(root); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值