您的位置:首页 > 其它

笔试:求二叉树中相差最大的两个节点间的差值绝对值

2014-08-31 10:34 399 查看
写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。

package org.algorithm;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class GetTreeNum {
private int[] array = { 11, 32, 6, 2, 14, 54, 37, 81, 49 };//定义array数组
private static List<TreeNode> nodeList = null;
//二叉树类TreeNode
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//利用array数组构造二叉树方法
public void createBinTree() {
nodeList = new LinkedList<TreeNode>();
// 将一个数组的值依次转换为Node节点
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
nodeList.add(new TreeNode(array[nodeIndex]));
}
// 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
// 左孩子
nodeList.get(parentIndex).left = nodeList.get(parentIndex * 2 + 1);
// 右孩子
nodeList.get(parentIndex).right = nodeList.get(parentIndex * 2 + 2);
}
// 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
int lastParentIndex = array.length / 2 - 1;
// 左孩子
nodeList.get(lastParentIndex).left = nodeList
.get(lastParentIndex * 2 + 1);
// 右孩子,如果数组的长度为奇数才建立右孩子
if (array.length % 2 == 1) {
nodeList.get(lastParentIndex).right = nodeList
.get(lastParentIndex * 2 + 2);
}
}
//定义获取最大差绝对值方法
public int getMaxAbsNum(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode p = root;
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
if (root == null)
return 0;
while (p != null || !s.isEmpty()) {
while (p != null) {
if (max < p.val)
max = p.val;
if (min > p.val)
min = p.val;
s.push(p);
p = p.left;
}
if (!s.isEmpty()) {
p = s.peek();
s.pop();
p = p.right;
}
}
return Math.abs(max - min);
}
//方法入口
public static void main(String[] args) {
GetTreeNum getTree = new GetTreeNum();
getTree.createBinTree();
// nodeList中第0个索引处的值即为根节点
TreeNode root = nodeList.get(0);
int size=getTree.getMaxAbsNum(root);
System.out.println(size);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐