2015阿里秋招当中一个算法题(经典)
2017-06-28 08:39
274 查看
写一个函数,输入一个二叉树,树中每一个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率
这是2015阿里秋招的一个在线笔试题
实现方法非常easy。遍历一遍二叉树,找出最大最小,一相减就能够求出最大的差值
之前在做题的时候竟然写递归的方法求值。后面測试了一下。果然结果不正确
仅仅要是非递归的的方法遍历都能够非常easy找出最大值最小值。效率也比較高,时间复杂度为O(n)。
以下是我用非递归从上往下遍历二叉树的方法
用队列容器就可以方便实现。
我写的代码:
这是2015阿里秋招的一个在线笔试题
实现方法非常easy。遍历一遍二叉树,找出最大最小,一相减就能够求出最大的差值
之前在做题的时候竟然写递归的方法求值。后面測试了一下。果然结果不正确
仅仅要是非递归的的方法遍历都能够非常easy找出最大值最小值。效率也比較高,时间复杂度为O(n)。
以下是我用非递归从上往下遍历二叉树的方法
用队列容器就可以方便实现。
我写的代码:
#include <iostream> #include <tchar.h> #include <queue> using namespace std; typedef struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight; }BinaryTreeNode ; int MaxT(BinaryTreeNode *pRoot) { int max=pRoot->m_nValue,min=pRoot->m_nValue; if(!pRoot) { return 0; } queue<BinaryTreeNode*>qTree; qTree.push(pRoot); while(!qTree.empty()) { BinaryTreeNode *pNode=qTree.front(); if(max<pNode->m_nValue) { max=pNode->m_nValue; } else if(min>pNode->m_nValue) { min=pNode->m_nValue; } qTree.pop(); if(pNode->m_pLeft) qTree.push(pNode->m_pLeft); if(pNode->m_pRight) qTree.push(pNode->m_pRight); } return max-min; } //以先序的方式构建二叉树,输入-1表示结点为空 void CreateBinaryTree(BinaryTreeNode *&pRoot) { int nNodeValue = 0; cin >> nNodeValue; if (-1== nNodeValue) { pRoot = NULL; return; } else { pRoot = new BinaryTreeNode(); pRoot->m_nValue = nNodeValue; CreateBinaryTree(pRoot->m_pLeft); CreateBinaryTree(pRoot->m_pRight); } } void PrintInOrder(BinaryTreeNode *&pRoot) { if (pRoot != NULL) { PrintInOrder(pRoot->m_pLeft); cout << pRoot->m_nValue << " "; PrintInOrder(pRoot->m_pRight); } } int _tmain(int argc, _TCHAR* argv[]) { BinaryTreeNode *pRoot = NULL; CreateBinaryTree(pRoot); cout <<"中序遍历为:"<<endl; PrintInOrder(pRoot); cout << endl; int maxabs=MaxT(pRoot); cout<<"最大绝对值为"<<maxabs<<endl; //vector<int> path; //FindPath(pRoot, 22, path); system("pause"); return 0; }
相关文章推荐
- 2015阿里秋招其中一个算法题(经典)
- 白话经典算法系列之中的一个 冒泡排序的三种实现
- 何恺明经典去雾算法 还北京一个碧洗蓝天?
- 【经典算法】:如何在一个函数里面返回多个值的实现
- 经典算法面试题目-翻转一个C风格的字符串(1.2)
- 经典算法一个数二进制中1的个数
- 一个经典的算法程序
- 阿里2015笔试附加题-一个数组中存在一组数字,其中有一个数字重复3遍,其他2遍,在O(1)空间找到那个重复3次的数
- 何恺明经典去雾算法 还北京一个碧洗蓝天?
- 只用getchar函数读入一个整数(算法竞赛入门经典 完整版)
- 【阿里2015校招面试算法题】辗转相除法求最小公约数
- 冒泡是一个经典算法
- 经典算法面试题目-翻转一个C风格的字符串(1.2)
- objective-c判断点是否在多边形内(包括在多边形上)的一个经典算法
- 白话经典算法系列之中的一个 冒泡排序的三种实现
- 在一个元素个数为N的数组里,找到升序排在N/5位置的元素的最优算法时间复杂度是----阿里巴巴2015实习生笔试题
- 经典的100个C算法__(4)将一个正整数分解质因数
- 白话经典算法系列之中的一个 冒泡排序的三种实现
- 【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】
- 一个洗牌程序算法,随机交换位置【经典】