题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树
则打印出三条路径:10, 12 和10, 5, 7、10,5,4,3
二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree { int m_nValue; // value of node BinaryTreeNode *m_pLeft; // left child of node BinaryTreeNode *m_pRight; // right child of node };
1.首先二元树的定义,我们在第一题已经查阅过了,所以知道其是什么意思
2.代码中,首先要有一个根据数组构造2元树的方法,返回根节点。
3.然后前序遍历树。节点的和好求,以及在什么情况下打印这些节点也很容易,关键的问题是如何保存这些经过的节点,当遍历到叶子节点还是不符合要求的时候,回到父节点后,如何删除之前遍历的叶子节点。
4.采用栈结构来保存经过的路径,当遍历该节点的时候,让该节点入栈。如果当前节点遍历完以后,就要把该节点出栈。在这之间,会有一个判断,如何满足要求,我们就打印栈信息。追个输出栈里面的内容。
package com.sprd.interview.algorithm; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Copyright 2014 TJ SPREADTRUM TEST_AF All Right Reserved * * @author: hui.qian Created on 2014年12月11日 上午9:15:53 Description: */ public class Problem4 { static int find = 0; Stack<Integer> mStack = new Stack<Integer>(); private void printPath(BSTreeNode node, int sum) { if (node == null) { return; } mStack.push(node.getValue()); sum += node.getValue(); if (find == sum) { printPath(); System.out.println("this path is right!"); } printPath(node.getLeft(), sum); printPath(node.getRight(), sum); mStack.pop(); } private void printPath() { for (Integer i : mStack) { System.out.println("path : " + i); } } // 由输入的值的数组得到根节点 private BSTreeNode buildTree(int[] bsTree, int begin) { int lIndex = 2 * begin + 1; int rIndex = 2 * begin + 2; int length = bsTree.length; BSTreeNode rootNode = new BSTreeNode(); rootNode.setValue(bsTree[begin]); if (lIndex < length) { rootNode.setLeft(buildTree(bsTree, lIndex)); } if (rIndex < length) { rootNode.setRight(buildTree(bsTree, rIndex)); } return rootNode; } public static void main(String[] args) { // TODO Auto-generated method stub Problem4 problem = new Problem4(); int[] nodeValue = { 10, 5, 12, 4, 7, 6, 9,3 }; BSTreeNode rootNode = problem.buildTree(nodeValue, 0); find = 22; int sum = 0; problem.printPath(rootNode, sum); } }
输出结果
path : 10 path : 5 path : 4 path : 3 this path is right! path : 10 path : 5 path : 7 this path is right! path : 10 path : 12 this path is right!