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


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

    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);
    	}
    
    }
    


  • 相关阅读:
    Spark基础知识详解
    jenkins shared library【demo】
    反if的活动
    开发工具vscode
    【火狐】查看和切换 本地服务 与 全球服务
    java【Socket】【上传下载文件】
    Android【照片备份】【折腾方案1】
    total commander【删除重复文件】
    jenkins【插件】【优先级】
    Android【照片备份】【折腾方案2】
  • 原文地址:https://www.cnblogs.com/wuyida/p/6300926.html
Copyright © 2020-2023  润新知