Created
September 8, 2013 13:16
-
-
Save tianweidut/6484646 to your computer and use it in GitHub Desktop.
Find path in binary tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//要找到某条路径,就需要进行二叉树的遍历,在此使用前序遍历: 父节点-> left ->right | |
//Tips: 1. 虽然使用了递归,但是每个结点维护自己的buffer,比较耗空间 | |
void findSum(TreeNode head, int sum, ArrayList<Integer> buffer, int level) | |
//head 是当前树的根节点, sum 是期望的路径和, | |
//buffer 是数组,可以看成stack, 每个结点对应着自己的buffer,值是从根节点按照前序遍历到自己的路径节点, | |
//这也是从其他节点到该节点的有效路径,如果对这个数组进行反向遍历,就得到了从某个结点到该节点的路径 | |
//level 只是为了遍历的时候简单,完全可以用ArrayList的长度,可以去掉这个参数 | |
{ | |
if(head == null) return; // 递归判断,终止条件 | |
int tmp = sum; | |
buffer.add(head.data); // 将当前节点值加入buffer中,对于这个buffer来说是最后一个元素了 | |
for(int i=level;i>-1;i--){ | |
tmp -= buffer.get(i); // 由于这个树是正负值都有的,所以要多判断,书上讲了 | |
if(tmp == 0) print(buffer, i, level); | |
} | |
//对整个buffer进行复制 | |
ArratList<Integer> c1= (ArrayList<Integer>) buffer.clone(); | |
ArratList<Integer> c2= (ArrayList<Integer>) buffer.clone(); | |
//递归对left和right进行处理 | |
findSum(head.left, sum, c1, level+1); | |
findSum(head.right, sum, c2, level+1); | |
} | |
//love xiaoxinxin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment