首页 > 其他 > 详细

p142 二叉搜索树的区间和(leetcode 938)

时间:2020-04-18 13:49:44      阅读:40      评论:0      收藏:0      [点我收藏+]

一:解题思路

方法一:递归法 Time:O(n),Space:O(n)

方法二:迭代法 Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

方法一C++:

class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) 
    {
        if (root == NULL) return 0;
        if (root->val < L) return rangeSumBST(root->right,L,R);
        if (root->val > R) return rangeSumBST(root->left,L,R);

        return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right,L,R);
    }
};

方法一Java:

class Solution {
        public int rangeSumBST(TreeNode root, int L, int R) 
        {
               if(root==null) return 0;
               if(root.val<L) return rangeSumBST(root.right,L,R);
               if(root.val>R) return rangeSumBST(root.left,L,R);
               
               return root.val+rangeSumBST(root.left,L,R)+rangeSumBST(root.right,L,R);
        }
    }

方法二C++:

class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) 
    {
        if (root == NULL) return 0;
        int sum = 0;
        stack<TreeNode*> s;
        s.push(root);

        while (!s.empty())
        {
            TreeNode* node = s.top();
            s.pop();
            if (node == NULL) continue;
            if (node->val < L) s.push(node->right);
            else if (node->val > R) s.push(node->left);
            else
            {
                sum += node->val;
                s.push(node->left);
                s.push(node->right);
            }
        }

        return sum;
    }
};

方法二Java:

class Solution {
        public int rangeSumBST(TreeNode root, int L, int R) 
        {
               if(root==null) return 0;
               int sum=0;
               Stack<TreeNode> s=new Stack<>();
               s.push(root);
               while (!s.empty())
               {
                   TreeNode node=s.pop();
                   if(node==null) continue;
                   
                   if(node.val<L) s.push(node.right);
                   else if(node.val>R) s.push(node.left);
                   else
                   {
                       sum+=node.val;
                       s.push(node.left);
                       s.push(node.right);
                   }
               }
               
               return sum;
        }
    }

 

p142 二叉搜索树的区间和(leetcode 938)

原文:https://www.cnblogs.com/repinkply/p/12725021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!