[编程题]二叉树-网易
[编程题] 二叉树
有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。
给定二叉树的根节点root,请返回所求距离。
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Tree { //先序遍历找到权重最大和最小叶节点 int res; void preorder(TreeNode* root, TreeNode* &small, TreeNode* &big) { if (!root) return; if (root->left == NULL && root->right == NULL)//是叶子节点 { if ((small == NULL) && (big == NULL)) { small = big = root; } else { if (root->val>big->val) big = root; if (root->val<small->val) small = root; } } preorder(root->left, small, big); preorder(root->right, small, big); } //计算两个节点之间的距离 int Dis(TreeNode* root, TreeNode* &small, TreeNode* &big) { //如果root是NULL if (root == NULL) return -1; //如果root==big 或者 root==small if (root == big || root == small) return 0; int left = Dis(root->left, small, big); int right = Dis(root->right, small, big); if (left >= 0 && right >= 0)//分别在左边和右边 { res=left+1+right+1; return left + 1 + right + 1; } if (left >=0 ) return left+1; if (right>=0) return right+1; if (left == -1 && right == -1) return -1; return -1; } public: int getDis(TreeNode* root) { TreeNode* small=NULL, *big=NULL; preorder(root, small, big); Dis(root, small, big); return res; } };