Find all paths with sum as a given value in a binary three

本文介绍了一个针对二叉搜索树的问题:寻找所有节点路径,使得这些路径上的节点值之和等于给定的目标值。提供了完整的Java实现代码,包括插入节点、中序遍历、前序遍历等功能,并展示了如何通过递归方式找到所有符合条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:
microsoft-interview-questions 57 Answers

Given a value and a binary search tree.
Print all the paths(if there exists more than one) which sum up to that value. It can be any path in the tree. It doesn't have to be from the root.

My code:
I also pasted my code at [url]http://www.careercup.com/question?id=2971[/url]


import java.util.Stack;

public class BinarySearchTree {

private class Node {
int data;
Node left;
Node right;
Node(int v, Node left, Node right){
data = v;
this.left = left;
this.right = right;
}
}

public Node root;

public void insertNode(int data) {
if (root == null) {
root = new Node(data, null, null);
return;
}
Node cur = root;
do {
if(data >= cur.data) {
if(cur.right != null) cur = cur.right;
else {
cur.right = new Node(data, null, null);
return;
}
}else {
if(cur.left != null) cur = cur.left;
else {
cur.left = new Node(data, null, null);
return;
}
}
}while(cur != null);
}

public void inorder() {
System.out.println("\nin-order :");
printSubTreeInOrder(root);
}

public void preorder() {
System.out.println("\npre-order :");
printSubTreePreOrder(root);
}

private void printSubTreeInOrder(Node p){
if(p.left != null) printSubTreeInOrder(p.left);
System.out.print("\t" + p.data);
if(p.right != null) printSubTreeInOrder(p.right);
}
private void printSubTreePreOrder(Node p){
System.out.print("\t" + p.data);
if(p.left != null) printSubTreePreOrder(p.left);
if(p.right != null) printSubTreePreOrder(p.right);
}
public void printAllPathWithSum(int sum){
Stack<Node> path = new Stack<Node>();
findPath(root, sum, path);
}

private void printPath(Stack<Node> path){
System.out.print("\nFind Path:");
for(Node n: path){
System.out.print("\t" + n.data);
}
}

private void findPath(Node p, int value, Stack<Node> path){
if(p == null) return;
if(p.data == value){
path.push(p);
printPath(path);
path.pop();
}else {
path.push(p);
if(p.left != null) findPath(p.left, value - p.data, path);
if(p.right != null)findPath(p.right, value- p.data, path);
path.pop();
}
if(p.left != null) findPath(p.left, value , path);
if(p.right != null)findPath(p.right, value, path);
}


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

BinarySearchTree tree = new BinarySearchTree();
tree.insertNode(5);
tree.insertNode(2);
tree.insertNode(7);
tree.insertNode(1);
tree.insertNode(3);
tree.insertNode(9);
tree.inorder();
tree.preorder();
tree.printAllPathWithSum(1);
tree.printAllPathWithSum(0);
tree.printAllPathWithSum(16);
tree.printAllPathWithSum(9);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值