zoukankan      html  css  js  c++  java
  • leetcode Path Sum

    题目:给定一颗数,以及一个数sum。判断是否存在从树到叶节点的和等于sum。

    例如:

    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    rerun true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    利用递归,和Minimum Depth类似,要考虑到叶节点才返回。很容易得到递归式子:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasPathSum(TreeNode *root, int sum) 
        {
            if (!root) return false;
            if (!root -> left && !root -> right) return sum == root -> val;
            bool lf = false, ri = false;
            
            if (root -> left)
                lf = hasPathSum(root -> left, sum - root -> val);
            if (root -> right)
                ri = hasPathSum(root -> right, sum - root -> val);
            return lf || ri;
        }
    };

    需要注意的是当叶子节点当根节点左右子树都为空是才为叶子节点,如果有一个飞空,那么根节点自身就不是叶子节点,所以不存在只有根节点的解。

    同时记录一下非递归的解

    public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
     
            LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
            LinkedList<Integer> values = new LinkedList<Integer>();
     
            nodes.add(root);
            values.add(root.val);
     
            while(!nodes.isEmpty()){
                TreeNode curr = nodes.poll();
                int sumValue = values.poll();
     
                if(curr.left == null && curr.right == null && sumValue==sum){
                    return true;
                }
     
                if(curr.left != null){
                    nodes.add(curr.left);
                    values.add(sumValue+curr.left.val);
                }
     
                if(curr.right != null){
                    nodes.add(curr.right);
                    values.add(sumValue+curr.right.val);
                }
            }
     
            return false;
        }
  • 相关阅读:
    Scite 编辑器及其相关项目介绍
    cmake 常用指令入门指南
    C++中的POD类型
    引用折叠、万能引用和完美转发那些事
    c++的对象初始化
    C++类对象的内存布局
    effective C++ 读书精华笔记提取
    c/c++的const说明符——深入挖掘
    gdb调试器—常用知识(一)
    g++/gcc编译器——常用知识(一)
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4132797.html
Copyright © 2011-2022 走看看