2 Sum in Binary Search Tree

Given a BST, find 2 nodes in it which sum to a given target

hint: 

Inorder traversal + BST + 2 SUM

* Time : O(N)

* Space: O(lgN)

  1 class TreeNode0 {
  2     int val;
  3     TreeNode0 left, right;
  4     public TreeNode0(int val) {
  5         this.val = val;
  6     }
  7 }
  8 public class BST2sum {
  9     public void bst2sum(TreeNode0 root, int target) {
 10         TreeNode0 left = root, right = root;
 11         TreeNode0 curl = root, curr = root;
 12         Stack<TreeNode0> stack0 = new Stack<TreeNode0>();
 13         Stack<TreeNode0> stack1 = new Stack<TreeNode0>();
 14         /*
 15          * Init, find the most-left and most-right node
 16          */
 17         while (curl != null || !stack0.isEmpty()) {
 18             if (curl != null) {
 19                 stack0.push(curl);
 20                 curl = curl.left;
 21             } else {
 22                 curl = stack0.pop();
 23                 left = curl;
 24                 curl = curl.right;
 25                 break;
 26             }
 27         }
 28         while (curr != null || !stack1.isEmpty()) {
 29             if (curr != null) {
 30                 stack1.push(curr);
 31                 curr = curr.right;
 32             } else {
 33                 curr = stack1.pop();
 34                 right = curr;
 35                 curr = curr.left;
 36                 break;
 37             }
 38         }
 39         while (right.val >= left.val) {
 40             System.out.println("left: "+left.val + ", right: "+right.val);
 41             if (left.val + right.val == target) {
 42                 System.out.println(left.val + ", " + right.val);
 43                 return;
 44             } else if (left.val + right.val < target) { // move left
 45                 while (curl != null || !stack0.isEmpty()) {
 46                     if (curl != null) {
 47                         stack0.push(curl);
 48                         curl = curl.left;
 49                     } else {
 50                         curl = stack0.pop();
 51                         left = curl;
 52                         curl = curl.right;
 53                         break;
 54                     }
 55                 }
 56             } else if (left.val + right.val > target) { // move right
 57                 while (curr != null || !stack1.isEmpty()) {
 58                     if (curr != null) {
 59                         stack1.push(curr);
 60                         curr = curr.right;
 61                     } else {
 62                         curr = stack1.pop();
 63                         right = curr;
 64                         curr = curr.left;
 65                         break;
 66                     }
 67                 }
 68             }
 69         }
 70         System.out.println("the target has not been found");
 71     }
 72     public static void main(String[] args) {
 73         TreeNode0 node0 = new TreeNode0(0);
 74         TreeNode0 node1 = new TreeNode0(3);
 75         TreeNode0 node2 = new TreeNode0(5);
 76         TreeNode0 node3 = new TreeNode0(6);
 77         TreeNode0 node4 = new TreeNode0(7);
 78         TreeNode0 node5 = new TreeNode0(9);
 79         TreeNode0 node6 = new TreeNode0(13);
 80         TreeNode0 node7 = new TreeNode0(17);
 81         TreeNode0 node8 = new TreeNode0(22);
 82         TreeNode0 node9 = new TreeNode0(23);
 83         node4.left = node2;
 84         node4.right = node6;
 85         node6.left = node5;
 86         node6.right = node8;
 87         node8.left = node7;
 88         node8.right = node9;
 89         node2.left = node0;
 90         node2.right = node3;
 91         node0.right = node1;
 92         BST2sum tree = new BST2sum();
 93         tree.bst2sum(node4, 11);
 94         tree.bst2sum(node4, 15);
 95         tree.bst2sum(node4, 18);
 96         tree.bst2sum(node4, 30);
 97     }
 98 }
 99 /*
100             7
101         /       102        5         13
103      /   \      /   104     0     6    9    22
105      \             /  106        3           17  23
107 */
时间: 2024-11-07 18:43:41

2 Sum in Binary Search Tree的相关文章

【leetcode】1038. Binary Search Tree to Greater Sum Tree

题目如下: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a t

UVA - 10304Optimal Binary Search Tree(递推)

题目:UVA - 10304Optimal Binary Search Tree(递推) 题目大意:给出一组数,e1 < e2 < ... < en,现在要求将这些数组成一棵二叉搜索树,并且使得sum (ei * cost(ei))最小.cost(ei)表示ei到到根节点之间有多少条边. 解题思路:首先二叉搜索树要满足左节点小于根节点,右节点大于根节点.因此对于e1 < e2 < ... < en这样一组数,我们只要枚举根节点的位置ek,将这个序列分成左右子树两部分(e

uva 10304 Optimal Binary Search Tree (区间DP)

uva 10304 Optimal Binary Search Tree 题目大意:给出N个结点(已知每个结点的权值)来建树,建树时要满足以下规则:左子树的节点的值要全小于父节点,右子树的节点的值要全大于父节点.要求最后建出的树总权值最小.总权值=各结点乘以层数(从0层开始)之后相加的和. 解题思路:dp[i][j]代表区间第i个结点到第j个结点组成的树最小的总权值.dp[j][i]=min(dp[j][i],dp[j][k?1]+dp[k+1][i]+sum[i]?sum[j?1]?num[k

uva 1264 - Binary Search Tree(BST)

题目链接:uva 1264 - Binary Search Tree 题目大意:给定一个插入顺序,要求输出有多少种插入顺序,使得生成的BST一样. 解题思路:组合数学+BST的性质,起始左右两个子树的节点之间是没有影响的.所以逐层递推上去即可. #include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int max

[Coding Made Simple] Optimal Binary Search Tree

Given keys and frequency at which these keys are searched, how would you create a binary search tree from these keys such that the cost of searching is minimum. The cost of searching is defined as the sum of all node's search frequency * its depth; R

LC.235.Lowest Common Ancestor of a Binary Search Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowe

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the nod

235. Lowest Common Ancestor of a Binary Search Tree

1. 问题描述 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T th

leetcode 109 Convert Sorted List to Binary Search Tree

题目连接 https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ Convert Sorted List to Binary Search Tree Description Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. /** * De