面试题34:二叉树中和为某一值的路径
原创
©著作权归作者所有:来自51CTO博客作者qq59ce45caba461的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的结点形成的一条路径。
分析:
使用前序遍历的方式访问某一结点时,把该结点添加到路径上,并累加该结点的值。如果该结点为叶结点,并且路径中结点值的和刚好等于输入的整数,当前路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父结点,因此,我们在函数退出之前要把路径上当前结点删除,并减去当前结点的值,以确保父结点路径刚好是从根节点到父结点。保存路径的数据结构是一个栈,因为路径要与递归调用状态一致,递归调用本质也是栈的入栈和出栈的过程。
解法:
package com.wsy;
import java.util.ArrayList;
import java.util.List;
class Tree {
private int value;
private Tree left;
private Tree right;
public Tree() {
}
public Tree(int value) {
this.value = value;
this.left = this.right = null;
}
public Tree(int value, Tree left, Tree right) {
this.value = value;
this.left = left;
this.right = right;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Tree getLeft() {
return left;
}
public void setLeft(Tree left) {
this.left = left;
}
public Tree getRight() {
return right;
}
public void setRight(Tree right) {
this.right = right;
}
}
public class Main {
public static void main(String[] args) {
Tree tree = init();
int k = 22;
List<Integer> list = new ArrayList<Integer>();
int sum = 0;
findPath(tree, k, sum, list);
}
public static Tree init() {
Tree tree5 = new Tree(7);
Tree tree4 = new Tree(4);
Tree tree3 = new Tree(12);
Tree tree2 = new Tree(5, tree4, tree5);
Tree tree1 = new Tree(10, tree2, tree3);
return tree1;
}
public static void findPath(Tree tree, int k, int sum, List list) {
if (tree == null) {
return;
}
int value = tree.getValue();
sum += value;
list.add(value);
int size = list.size();
if (sum == k && tree.getLeft() == null && tree.getRight() == null) {
System.out.println("findPath:");
for (int i = 0; i < size; i++) {
System.out.print(list.get(i) + "\t");
}
System.out.println();
}
if (tree.getLeft() != null) {
findPath(tree.getLeft(), k, sum, list);
}
if (tree.getRight() != null) {
findPath(tree.getRight(), k, sum, list);
}
list.remove(size - 1);// 返回父结点之前,将当前结点删除
}
}