typedef struct node { int data; struct node *plChild; struct node *prChild; }*BiTreePtr; int find_max_diff(node *root) { static int min = MAX_INF;//初始化为一个足够大的值 static int max = MIN_INF;//初始化为一个足够小的值 if (root->data < min) min = root->data; if (root->data > max) max = root->data; if (root->plChild != NULL) find_max_diff(root->plChild); if (root->prChild!= NULL) find_max_diff(root->prChild); return max - min; }
#include<iostream> #include<string> #include <vector> #include <queue> using namespace std; struct NODE { int data; NODE *left; NODE *right; }node; //首先广度优先遍历一棵树,将值放入一个容器,然后对容器中的数遍历一次获取最大值和最小值 int find(NODE* list) { vector<int> v; queue<NODE*> q; NODE* p; if (NULL==list) { return 0; } q.push(list); while (!q.empty()) { p = q.front(); if (p->left!=NULL) { q.push(p->left); } if (p->right!=NULL) { q.push(p->right); } q.pop(); v.push_back(p->data); } int mi=v.front(); int ma=v.front(); for (int i = 0;i < v.size();i++) { if (v[i]<mi) { mi = v[i]; } if (v[i]>ma) { ma=v[i]; } } return (ma-mi); }
static int min = 0; static int max = 0; public static int findMaxSubM(TreeNode root){ if(root==null){ return 0; } min = root.val; max = root.val; inOrder(root); System.out.println(" main===min= " + min + " max= " + max); return Math.abs(max-min); } public static void inOrder(TreeNode node){ if(node==null){ return; } min = Math.min(min, node.val); max = Math.max(max, node.val); System.out.println(" min= " + min + " max= " + max); if(node.left!=null){ inOrder(node.left); } if(node.right!=null){ inOrder(node.right); } }
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
};
int maxDiffValue(TreeNode* pRoot)
{
if(pRoot==nullptr)
{
return 0;
}
int min=pRoot->val;
int max=pRoot->val;
maxDiffValueCore(pRoot,max,min);
return (max-min);
}
void maxDiffValueCore(TreeNode* pRoot,int& max,int& min)
{
if(pRoot==nullptr)
{
return;
}
if(pRoot->val>max)
max=pRoot->val;
if(pRoot->val<min)
min=pRoot->val;
maxDiffValueCore(pRoot->left,max,min);
maxDiffValueCore(pRoot->right,max,min);
}