第八周LeetCode

来源:互联网 发布:阿里弹性云 编辑:程序博客网 时间:2024/06/08 13:28

题目
难度 Easy

Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22.
这里写图片描述
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

实现思路

题目要找一条从根节点到叶子节点的路径,使得这条路径长度等于输入的长度,如果不存在返回0否则返回1。由于要找的是从根到叶子节点的路径,可以先搜索根节点,然后分别对根节点的左子节点和右子节点做深度优先搜索,若在左子树中找到路径就返回true,否则在右子树中找,找到就返回true否则返回false。由于输入是一个二叉树,此做法就相当于对二叉树根节点进行先序遍历。算法的时间复杂度为O(h),h为二叉树高度。

实现代码

void preOrder(TreeNode* root, int &count, const int sum, bool &flag) {    count += root->val;    if (count == sum && root->left == NULL && root->right == NULL) {        flag = true;    }    //如果找到就返回    if (flag) {        return;    }    if (root->left) {        preOrder(root->left, count, sum, flag);    }    //如果在左子树中找到就返回    if (flag) {        return;    }    //如果找不到就回溯    if (root->left) count -= root->left->val;    if (root->right) {        preOrder(root->right, count, sum, flag);    }    //如果找不到就回溯    if (root->right) count -= root->right->val;}bool hasPathSum(TreeNode* root, int sum) {    int count = 0;    if (root)  count = root->val;    else return false;    //只有根节点,且输入的长度即为根节点的权值    if (count == sum && root->left == NULL && root->right == NULL) return true;    bool flag = false;    if (root->left) {        preOrder(root->left, count, sum,flag);    }    count = root->val;    if (!flag && root->right) {        preOrder(root->right, count, sum,flag);    }    return flag;}