考察点
树的遍历
知识点
题目
分析
这道题目用的也是归纳大法,多举一些例子就可以找到规律了。题目中树的路径的定义是从根结点开始一直到叶子结点形成的一条路径,所以最先遍历的结点一定是根结点,假设遍历完10,5,4,接下来应该要遍历10,5,7了,这个时候能发现10,5都还在,同样10,5,4和10,5,7都遍历完遍历10,12的时候,10还在,因此我们需要一个数据结构来存这些数据,而观察数据发现是最先进去的数据最后出来,因此用栈最合适不过了,在左子树遍历完开始遍历右子树的时候需要把左子树的元素都弹出去,这样才能保证左右子树的根结点到右子树组成一个新的路径
public class Node{
int val;
Node leftChild;
Node rightChild;
public Node(int data) {
this.val = data;
this.leftChild = null;
this.rightChild = null;
}
}
import java.util.Deque;
import java.util.Iterator;
public class BinaryTree {
Node root;
public BinaryTree() {
this.root = null;
}
public void insertTree(int val) {
if (this.root == null) {
Node root = new Node(val);
this.root = root;
} else {
insertChildTree(this.root,val);
}
}
public void insertChildTree(Node node,int val) {
if (node != null && val < node.val) {
if (node.leftChild == null) {
node.leftChild = new Node(val);
} else {
insertChildTree(node.leftChild,val);
}
}
if (node != null && val > node.val) {
if (node.rightChild == null) {
node.rightChild = new Node(val);
} else {
insertChildTree(node.rightChild,val);
}
}
}
public Node getRoot() {
return this.root;
}
public void isPathSum(Node root,Deque stack,int value,int currentSum) {
if (root == null) {
return;
}
stack.push(root.val);
currentSum = currentSum + root.val;
if (root.leftChild == null && root.rightChild == null) {
if (currentSum == value) {
Iterator dequeIt = stack.iterator();
while (dequeIt.hasNext()) {
int val = (int) dequeIt.next();
System.out.print(val + " ");
}
System.out.println();
}
}
isPathSum(root.leftChild,stack,value,currentSum);
isPathSum(root.rightChild,stack,value,currentSum);
stack.pop();
currentSum = currentSum - root.val;
}
}
import java.util.Deque;
import java.util.LinkedList;
public class TwentyFive {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insertTree(10);
binaryTree.insertTree(5);
binaryTree.insertTree(12);
binaryTree.insertTree(4);
binaryTree.insertTree(7);
Deque<Integer> stack = new LinkedList<>();
binaryTree.isPathSum(binaryTree.getRoot(),stack,22,0);
}
}