剑指offer面试题22 二叉树中和为某一值的路径

考察点

树的遍历

知识点

题目

分析
这道题目用的也是归纳大法,多举一些例子就可以找到规律了。题目中树的路径的定义是从根结点开始一直到叶子结点形成的一条路径,所以最先遍历的结点一定是根结点,假设遍历完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);
	}

}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值