题解 | #二叉树的深度#

二叉树中和为某一值的路径(一)

http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 
 * @param sum int整型 
 * @return bool布尔型
 */
#include <stdbool.h>
bool hasPathSum(struct TreeNode* root, int sum ) {
    // write code here
    //一、层序遍历没整个子数,每遇到一个结点就将他的子节点值改变为子节点值+自己的值,用非递归的方式,用队列。空间复杂度n,时间复杂度n,
    //二、先遍历一遍树,求树的高度,然后根据树的高度用DFS算法进行搜索。
    struct TreeNode* Queue[10001];//建立一个队列
    struct TreeNode* temp;
    int rear = 0;
    int front = 1;
    if(!root){
        return false;
    }
    Queue[front] = root; 
    while(  rear != front ){
        temp = Queue[++rear];
        if(!temp->left && !temp->right){
            if(temp->val == sum)
                return true;
        }
        if(temp->left){
            Queue[++front] = temp->left;
            Queue[front]->val = temp->val + Queue[front]->val;
        }
        if(temp->right){
            Queue[++front] = temp->right;
            Queue[front]->val = temp->val + Queue[front]->val;          
        }
        
    }
   
    return false;
    
}














全部评论

相关推荐

野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务