首页 > 试题广场 >

写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函

[问答题]
写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。
int find(BiTree *T)//前序遍历的方法
{
if(*T==NULL) return -1;

static int max=0;
static int min=0;
if(min>(*T)->data)
min=(*T)->data;
if(max<(*T)->data)
max=(*T)->data;
if((*T)->lchild!=NULL)
find(&(*T)->lchild);
if((*T)->rchild!=NULL)
find(&(*T)->rchild);
return max-min;
}

发表于 2015-08-17 11:40:49 回复(0)
采用队列层序遍历
int compute(BinaryTreeNode* pNode)
{
std::queue<BinaryTreeNode*> qu;
int max=pNode->value;
int min=pNode->value;
    BinaryTreeNode* node=pNode;
qu.push(node);
while(qu.size()!=0)
{   node=qu.front();
   qu.pop();
if(node->left!=NULL)
qu.push(node->left);
if(node->right!=NULL)
qu.push(node->right);
if(node->value>max)
max=node->value;
else if(node->value<min)
min=node->value;
}
cout<<"max="<<max<<",min="<<min<<endl;
return max-min;
}
发表于 2015-08-11 23:33:52 回复(0)
xmm头像 xmm
//用先序编列,加类似选择排序的方法进行

package com.binary.abs.max;

import java.util.*;

class BinaryNode{
int a;
BinaryNode leftNode=null;
BinaryNode rightNode=null;
}

public class BinaryTree {
//在这里我就定义一个二叉树的点类
     BinaryNode root;
//在构造函数中初始化一个二叉树
public BinaryTree(BinaryNode root)
{
this.root=root;
}
//在这里定义方法,用先序遍历的方法来做
 //先在这里写一个先序遍历,再改,把遍历的值放到list中去
public int preOrderTraverseFind(BinaryNode node)
{
if(node==null)
{
return -1;
}
int min=node.a;
int max=node.a;
//List<BinaryNode> list=new ArrayList<BinaryNode>();
Stack<BinaryNode> stack=new Stack<BinaryNode>();
stack.push(node);
while(!stack.isEmpty())
{
BinaryNode tNode=stack.pop();
//在这里做判断
 if(tNode.a<=min)
 {
 min=tNode.a;
 }
 if(tNode.a>=max)
 {
 max=tNode.a;
 }
 
if(tNode.rightNode!=null)
{
stack.push(tNode.rightNode);
}
if(tNode.leftNode!=null)
{
stack.push(tNode.leftNode);
}
}
return max-min;
}

//在这里做测试,问题是怎么做测试呢
public  static void main(String args[])
{
BinaryNode A=new BinaryNode();
BinaryNode B=new BinaryNode();
BinaryNode C=new BinaryNode();
BinaryNode D=new BinaryNode();
BinaryNode E=new BinaryNode();
BinaryNode F=new BinaryNode();
A.a=1;  A.leftNode=B; A.rightNode=C;
B.a=2;  B.leftNode=D; B.rightNode=E;
C.a=3;  C.leftNode=F;  
D.a=4;  
E.a=5;
F.a=6;
BinaryTree bt=new BinaryTree(A);//构造一个二叉树
   long start=System.currentTimeMillis();
int iTemp=bt.preOrderTraverseFind(A);
long end=System.currentTimeMillis();
long l=start-end;
        System.out.println("消耗的时间为:"+l);
System.out.println(iTemp);
}
}
发表于 2015-08-20 01:15:10 回复(0)
public class Main
{
public static void main(String[] args) {
BinaryTree tree=new BinaryTree(3);
tree.lchild=new BinaryTree(1);
tree.lchild.lchild=new BinaryTree(2);
tree.lchild.rchild=new BinaryTree(10);
tree.rchild=new BinaryTree(5);
tree.rchild.rchild=new BinaryTree(14);
System.out.println(new Main().getValue(tree));
}
private static int max=Integer.MIN_VALUE;
private static int min=Integer.MAX_VALUE;
private static int result=Integer.MIN_VALUE;
public static int getValue(BinaryTree root){
if(root==null){
System.out.println("erro");
return -1;
}
return digui(root);
}
public static int digui(BinaryTree root){
if(root.value>max){
max=root.value;
}
if(root.value<min){
min=root.value;
}
if(result<Math.abs(max-min)){
result=Math.abs(max-min);
}
if(root.lchild!=null){
digui(root.lchild);
}
if(root.rchild!=null){
digui(root.rchild);
}
return result;
}
}

class BinaryTree
{
BinaryTree lchild;
BinaryTree rchild;
int value;
BinaryTree(int value){
this.value=value;
}
}

发表于 2015-08-19 22:40:50 回复(1)
int find(BinaryTreeNode *pRoot)
{
static int min = MIN;//定义一个足够大的数
static int max = MAX;//定义一个足够小的数
if(min>pRoot->val)
min = pRoot->val;
if(max<pRoot->val)
max = pRoot->val;
if(pRoot->lChild!=NULL)
find(pRoot->lChild);
if(pRoot->rChild!=NULL)
find(pRoot->rChild);
return max-min;
}

发表于 2015-08-12 18:03:27 回复(0)
/**
*1)先构造二叉树;
*2)利用二叉树遍历的方法得到min和max即可;
*/
class Test{
        public static void main(String[] args) {
		TestALBB mTestALBB=new TestALBB();
		int array[]={1,5,-5,9,-10};
		mTestALBB.createTree(array);
		int value=mTestALBB.getMax();
		System.out.println("value: "+value);
        }
}
class TestALBB{
	public int min=0;
	public int max=0;
	public TreeNode t=null;
	/*
	 * 有一组数据 构造二叉树;
	 */
	public void createTree(int array[]){
		//方法1--》顺序存储构造二叉排序树;利用队列;
		TreeNode t=new TreeNode();
		t.data=array[0];
		t.left=t.right=null;
		int i=1;
		java.util.Queue<TreeNode> mQueue=new java.util.LinkedList<TreeNode>();
		mQueue.offer(t);
		TreeNode temp=null;
		while(i<array.length-1){
			temp=mQueue.poll();
			TreeNode left=new TreeNode();
			left.data=array[i];
			left.left=left.right=null;
			temp.left=left;
			mQueue.offer(left);
			
			TreeNode right=new TreeNode();
			right.data=array[i+1];
			right.left=right.right=null;
			temp.right=right;
			mQueue.offer(right);	
			i=i+2;
		}
		this.t=t;
	}
/*
 * 利用先序排序得到 min和 max
 */
	public void getValue(TreeNode t){
		if(t!=null){
			if(t.data>max)max=t.data;
			else if(t.data<min)min=t.data;	
		}
		if(t.left!=null){
			getValue(t.left);
		}
		if(t.right!=null){
			getValue(t.right);
		}
	}
	 public int getMax(){
		this.getValue(this.t);
		return Math.abs(max-min);
	}
}
/**
 * 
 * @author Administrator
 * 节点的数据结构
 *
 */
class TreeNode{
	public TreeNode right=null;
	public TreeNode left=null;
	public int data=0;
}

发表于 2015-08-22 10:15:48 回复(1)
//TreeNode的数据结构
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val = val;
}
}
//方法主体
//我的想法是,遍历树结构,取出所有节点的值,然后放入一个数组中,最后找出这个数组中最大的值和最小的值,相减取绝对值即可
public int maxValue(TreeNode treeNode){
if(treeNode == null || treeNode.length==0){
return 0;
}
int[] array = new int[treeNode.size];
while(treeNode !=null){
array.add(treeNode.val);
if(treeNode.next == null){
break;
}
treeNode = treeNode.next;
}
min = Math.min(array);
max = Math.max(array);
return Math.abs(max-min);
}
发表于 2021-03-16 16:24:22 回复(0)
public class test1 {
    
    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }

    }
    public void dfs(TreeNode root,int [] dp) {
        if(root == null)
            return;
        dp[0] = Math.min(dp[0], root.val);
        dp[1] = Math.max(dp[1], root.val);
        dfs(root.left, dp);
        dfs(root.right, dp);
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] dp = new int[2];
        dp[0] = Integer.MAX_VALUE;
        dp[1] = Integer.MIN_VALUE;
        TreeNode root = new TreeNode(0);
        TreeNode left = new TreeNode(5);
        TreeNode right = new TreeNode(12);
        left.left = new TreeNode(0);
        left.right = new TreeNode(-4);
        root.left = left;
        right.left = new TreeNode(3);
        right.right = new TreeNode(4);
        root.right = right;
        new test1().dfs(root, dp);
        System.out.println(dp[1] - dp[0]);
    }

}

发表于 2020-03-29 19:59:33 回复(0)
 
发表于 2017-08-23 09:53:13 回复(0)
struct TreeNode
{
   int val;
   TreeNode *left;
   TreeNode *right;
};

int solve(TreeNode *root)
{
   if (root == NULL) return -1;
   int ma = 0, mi = 0;
   queue<TreeNode *> que;
   TreeNode *p = root;
   que.push(p);
   ma = max(ma, p->val);
   mi = min(mi, p->val);
   while (!que.empty())
   {
      TreeNode *q = que.top();
      que.pop();
      if (q->left) 
      {
         que.push(q->left);
         ma = max(ma, q->left->val);
         mi = min(mi, q->left->val);
       }
       if (q->right)
       {
          que.push(q->right);
          ma = max(ma, q->right->val);
          mi = min(mi, q->right->val);
       }
     }
     return ma - mi;
}

发表于 2016-04-19 12:24:53 回复(0)
public class BiTree {
	private Node root;
	private static int max;
	private static int min;

	/**
	 * 创建内部节点类
	 **/
	private class Node {
		// 左节点
		private Node leftChild;
		// 右节点
		private Node rightChild;
		// 节点对应的值
		private int data;

		public Node(int data) {
			leftChild = null;
			rightChild = null;
			this.data = data;
		}
	}// class Node

	public BiTree() {
		root = null;
	}

	/*
	 * 递归的创建二叉树
	 */
	public void buildTree(Node node, int data) {
		if (root == null) {// 如果根节点为空,创建根节点
			root = new Node(data);
		} else {
			if (data < node.data) {// 插入到左子树
				if (node.leftChild == null) {// 左节点为空,直接创建值为data的左节点
					node.leftChild = new Node(data);
				} else {// 左节点不为空,调用buildTree函数插到左子树中
					buildTree(node.leftChild, data);
				}
			} else {
				if (node.rightChild == null) {
					node.rightChild = new Node(data);
				} else {
					buildTree(node.rightChild, data);
				}
			}
		}
	}// end buildTree

	public int getMax(Node node) {
		if (node != null) {
			max = Math.max(max, node.data);
			getMax(node.rightChild);
		}
		return max;
	}

	public int getMin(Node node) {
		if (node != null) {
			min = Math.min(min, node.data);
			getMin(node.rightChild);
		}
		return min;
	}
	public static void main(String ars[]) {
		int[] a = { 6, 4, 8, 3, 5, 7, 9 };
		BiTree binTree = new BiTree();
		for (int i = 0; i < a.length; i++) {
			binTree.buildTree(binTree.root, a[i]);
		}
		min = binTree.root.data;
		// System.out.println("前序遍历");
		max = binTree.getMax(binTree.root);
		min = binTree.getMin(binTree.root);
		System.out.println(max - min);
	}
}


发表于 2016-04-14 01:02:42 回复(1)
设最大值和最小值为前两个元素中较大的元素和较小的元素,遍历二叉树,每次更新最大值最小值,遍历完二叉树返回最大值最小值的差。
发表于 2015-08-22 20:47:39 回复(0)
int distance(Tree* head){
  if(NULL==head) return 0;
  int min,max;
  min=max=head->value;
  distance(head->ltree,min,max);
  distance(head->rtree,min,max);
  return (max-min);
}
void distance(Tree* head, int& min, int &max){
  if(NULL==head) return;
  if(min>head->value) min=head->value;
  if(max<head->value)max=head->value;
  distance(head->ltree,min,max);
  distance(head->rtree,min,max);
}
编辑于 2015-08-24 09:40:03 回复(0)
<pre class="prettyprint lang-java">public class obtainMax{ public doublegetMax(Btree btr){ double max=0,min=0,k; node headnode = btr.gethead(); node templnode=null; node temprnode=null; if(headnode!=null){ max = headnode.getvalue(); templnode = headnode.getltree(); temprnode = headnode.getrtree(); <span></span> while(templnode !=null){ k= templnode .getvalue(): if(k&gt;max){ max = k; }else{ mix=k; } &nbsp;templnode =templnode .getltree(); } while(temprnode !=null){<span></span></pre> <pre class="prettyprint lang-java"> k= temprnode .getvalue(): if(k&gt;max){ max = k; }else{ mix=k; } &nbsp;temprnode =temprnode .getltree(); } return abs(max-min);</pre> <pre class="prettyprint lang-java"> } } }</pre> <br />
发表于 2015-08-22 14:43:53 回复(0)
遍历查找最大最小值
发表于 2015-08-18 10:22:27 回复(0)
<div> 就是遍历二叉树,找出最大值和最小值。假设二叉树采用数组实现,则时间复杂度可以达到O(n),空间复杂度为O(1)。<br /> <pre class="prettyprint lang-java">public class BinaryTree { public static void main(String[] args) { int[] tree = { 1, 2, 3, -1, 9, -1, 10, 4, 5, 8 }; System.out.println("树中节点最大差值为: " + getMaxGapofNodes(tree)); } // int[] tree = {1,2,3,-1,9,-1,10,4,5,8},-1表示该位置无节点 public static int getMaxGapofNodes(int[] tree) { int result = 0; int maxindex = 0; int minindex = 0; // 遍历找最大值和最小值 if (tree != null &amp;&amp; tree.length &gt; 0) { maxindex = minindex = 0; for (int i = 1; i &lt; tree.length; i++) { if (tree[i] &gt; 0) { if (tree[i] &gt; tree[maxindex]) maxindex = i; if (tree[i] &lt; tree[minindex]) minindex = i; } } } result = tree[maxindex] - tree[minindex]; return result; } } </pre> <br /> </div>
发表于 2015-08-16 10:26:05 回复(0)
递归实现,时间复杂度O(n);
typedef struct BiTNode{
char vex;
int data;
BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void getMaxAndMin(BiTree *T,int *max,int *min){
if(*T){
*max = (*T)->data > *max?(*T)->data:*max;
*min = (*T)->data < *min?(*T)->data:*min;
getMaxAndMin(&(*T)->lchild,max,min);
getMaxAndMin(&(*T)->rchild,max,min);
}
}
发表于 2015-08-15 21:20:12 回复(0)
//遍历的同时维护最大值,最小值
//时间复杂度 o(n)
public class MaxDifference { private int result = Integer.MIN_VALUE; private int max = Integer.MIN_VALUE; private int min = Integer.MAX_VALUE; public int maxDifference(TreeNode root){ if (root == null) { System.out.print("error"); return -1; } return preOrder(root); } public int preOrder(TreeNode root){ if(root.val > max) max = root.val; if(root.val < min) min = root.val; if (result < Math.abs(max - min)) { result = Math.abs(max - min); } if (root.left != null) { preOrder(root.left); } if (root.right != null){ preOrder(root.right); } return result; } }

发表于 2015-08-14 14:37:23 回复(0)
package conmon.niuke;

import java.util.HashMap;
import java.util.Map;

/**
 * 写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。
 * 
 * @author luchunlong
 *
 * 2015年8月12日 上午11:01:38
 */
public class AbsoluteCounter {
public class Node{
public Node(int value){
this.value=value;
}
Node lchild;
Node rchild;
int value;
}
public void getAbsoluteValue(Node tree,Map<String,Integer> result){
   if(tree.value < result.get("MIN")){
    result.replace("MIN", tree.value);
   }else if(tree.value > result.get("MAX")){
    result.replace("MAX", tree.value);
   }
   
   if(tree.lchild!=null){
    getAbsoluteValue(tree.lchild, result);
   }
   if(tree.rchild!=null){
    getAbsoluteValue(tree.rchild, result);
   }
}
public static void main(String[] args){
   Map<String,Integer> result=new HashMap<String,Integer>(); 
AbsoluteCounter counter=new AbsoluteCounter();
Node tree=counter.new Node(4); 
tree.lchild=counter.new Node(18); 
tree.lchild.lchild=counter.new Node(2); 
tree.lchild.rchild=counter.new Node(6); 
tree.rchild=counter.new Node(3); 
tree.rchild.lchild=counter.new Node(7);
result.put("MIN", tree.value);
result.put("MAX", tree.value);
counter.getAbsoluteValue(tree, result);
System.out.println("MIN:"+result.get("MIN"));
System.out.println("MAX:"+result.get("MAX"));
}

}

发表于 2015-08-12 11:39:11 回复(2)
int min,max;
int find(TreeNode * root)
{
min = root->value;
max = root->value;
findRecursive(root);
return max - min;
}
findRecursive(TreeNode * root)
{
if(root->left != NULL)
  {
  if(root->left->value<min)
  {
min = root->left->value;
}
if(root->left->value>max)
        {
            max = root->left->value;
        }
         findRecursive(root->left);
}
if(root->right != NULL)
    {
         if(root->right->value<min)
         {
             min = root->right->value;
         }
         if(root->right->value>max)
        {
            max = root->right->value;
        }
         findRecursive(root->right);
}
}

发表于 2015-08-04 12:06:59 回复(0)