/**
* 二叉树中和为某一值的路径
* 递归迭代的过程
* */
public class A04 {
public Stack<Node> stack = new Stack<Node>();
static class Node{
public int content;
public Node Left;
public Node Right;
public int getContent() {
return content;
}
public void setContent(int content) {
this.content = content;
}
public Node getLeft() {
return Left;
}
public void setLeft(Node left) {
Left = left;
}
public Node getRight() {
return Right;
}
public void setRight(Node right) {
Right = right;
}
public Node(int value){
content = value;
}
}
static class Tree{
public final Node rootNode = new Node(10);
public Node getRootNode () {
Node node5 = new Node(5);
rootNode.setLeft(node5);
Node node6 = new Node(6);
node5.setLeft(node6);
Node node7 = new Node(7);
Node node11 = new Node(11);
Node node1 = new Node(1);
Node node2 = new Node(2);
node11.setLeft(node1);
node11.setRight(node1);
node1.setLeft(node2);
node7.setLeft(node2);
rootNode.setRight(node11);
node5.setRight(node7);
return rootNode;
}
}
/**
* @param args
*/
public static void main(String[] args) {
Tree tree = new Tree();
int sum = 24;
A04 a4 = new A04();
a4.findSumPath(tree.getRootNode(),sum);
}
/**
*
*/
private void findSumPath(Node node ,int sum) {
if(node == null){
return ;
}
if(node.getContent() > sum){
return ;
}
if(node.getContent() < sum){
stack.push(node);//压栈
if(node.getLeft() != null){
findSumPath(node.getLeft(), sum-node.getContent());
}
if(node.getRight() != null){
findSumPath(node.getRight(), sum-node.getContent());
}
}
if(node.getContent() == sum){
stack.push(node);//如果节点是合适的,压栈后,打印出栈
print(stack);
stack.pop();
return;
}
stack.pop();//如果节点不合适,直接的出栈
}
/**
* @param stack2
*/
private void print(Stack<Node> stack2) {
for(Node node:stack2){
System.out.print(node.content + " ");
}
}
}
二叉树中和为某一值的路径
最新推荐文章于 2022-01-05 17:05:44 发布