题目
思路
由于要从根节点打印到叶子结点,并且采用回溯的思想,对二叉树的遍历采用 前序遍历
每次遍历到节点时,都判断当前的和是否等于给定的数字并且是否为叶子节点,如果不是叶子节点,继续前序遍历,并且将节点放入stack中 。
如果到了叶子节点,当前的结果等于给定数字,输出栈即可
如果不等于 ,就要回溯到其父节点,遍历父节点的另一个叶子结点。
例如,
如果到达4,发现结果并不等于index,则返回到3节点(此时需要将节点4 从栈中出栈),遍历3的右节点6。
代码实现
/**
*
*/
package buffer;
import java.util.Stack;
/***
* @author 18071
* @Date 2019年3月11日
* 功能:二叉树路径和为给定值
*
***/
public class test {
/***
* @author SG CV-6
* @Date 2019年3月11日
* 功能:
* @param args
*
*
* 3
* 4 6
*
*
*
***/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root =new TreeNode (1);
root.right=new TreeNode (3);
root.left=new TreeNode (3);
root.left.left=new TreeNode (7);
root.right.right=new TreeNode(17);
Solution s =new Solution ()
;
s.findpath(11, root);
}
}
class Solution{//前序遍历 二叉树---回溯思维,递归实现
void findpath(int k ,TreeNode root) {
int cursum=0;//当前的路劲值的和
Stack pathstack =new Stack();//用于保存路劲信息
findcore(k,root,pathstack,cursum);
}
/***
* @author SG CV-6
* @Date 2019年3月11日
* 功能:
* @param k
* @param root
* @param pathstack
* @param cursum
***/
private void findcore(int index, TreeNode root, Stack pathstack, int cursum) {
// TODO Auto-generated method stub
if(root==null) {
return;
}
pathstack.push(root.val);
cursum+=root.val;
if(cursum==index&&root.isleaf()) {//当 此时的和为index 且 到达叶子结点
while(!pathstack.isEmpty()) {
System.out.println(pathstack.pop());
}
}
if(root.left!=null) {//左节点不为空
findcore(index,root.left,pathstack,cursum);
}
if(root.right!=null) {//右节点
findcore(index,root.right,pathstack,cursum);
}
//是叶子节点,但是不符合要求 ,栈中删除此节点---(回溯)
cursum=cursum-root.val;
if(!pathstack.isEmpty()) {
pathstack.pop();
}
}
}
class TreeNode {
TreeNode left;
TreeNode right;
int val;
TreeNode(int x) {
this.val = x;
}
boolean isleaf() {
if(this.left==null&&this.right==null) {
return true;
}
else {
return false;
}
}
}
结果截图