zoukankan      html  css  js  c++  java
  • SPOJ NICEBTRE

    传送门

    Description

    Binary trees can sometimes be very difficult to work with. Fortunately, there is a class of trees with some really nice properties. A rooted binary tree is called “nice”, if every node is either a leaf, or has exactly two children.

    For example, the following tree is nice,

    nice tree

    but the following tree is not.

    not a nice binary tree

    The leaves of a nice binary tree are labeled by the letter ‘l’, and other nodes are labeled by the letter ‘n’.

    Given the pre-order traversal of a nice binary tree, you are required to find the depth of the tree.

    Notes : 

    1. The depth of a tree is defined as the length of the longest path with one end at the root.

    2. The pre-order traversal of the tree in the first image above produces the string “nlnnlll”.

    Input

    The first line contains the number of test cases T. T lines follow. Each line contains a string, which represents the pre-order traversal of a “nice” binary tree. Leaves are represented by the letter ‘l’ and other nodes by the letter ‘n’. The input is guaranteed to be the preorder traversal of a nice binary tree.

    0 < T < 20

    Length of the input string in each test case is at most 10000.

    Output

    Output one line for each test case, containing a single integer, the depth of tree.

    Sample Input

    3
    l
    nlnll
    nlnnlll

    Sample Output

    0
    2
    3

     

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 10005;
    char str[maxn];
    int pos,height;
    
    void dfs(int depth){
    	pos++;
    	height = max(depth,height);
    	if (str[pos] == '')	return;
    	if (str[pos] == 'l')	return;
    	if (str[pos] == 'n'){
    		dfs(depth + 1);  //left
    		dfs(depth + 1);  //right;
    	}
    }
    
    
    int main(){
    	int T;
    	scanf("%d",&T);
    	while (T--){
    		memset(str,0,sizeof(str));
    		height = 0,pos = -1;
    		scanf("%s",str);
    		dfs(0);
    		cout << height << endl;
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    02 python网络爬虫《Http和Https协议》
    09 Django之orm中的锁和事务
    08 Django之自定义标签和过滤器
    07 Django之配置静态文件以及渲染图片
    06 Django之模型层---多表操作
    05 Django之模型层---单表操作
    Spring 中的 18 个注解,你会几个?
    一个 Java 对象到底有多大?
    面试题:InnoDB中一棵B+树能存多少行数据?
    Elasticsearch如何做到亿级数据查询毫秒级返回?
  • 原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/7301705.html
Copyright © 2011-2022 走看看