You have the following definition of a TreeNode, which stores a node in a binary tree:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
|
In case those last three lines look a little confusing to you, those are three constructors: You can construct a tree node with a value of 0 and no children, a tree node with a given value and no children, or a tree node with a given value and given children.
Your job is to write the method minDiffInBST in the class Solution, with the following prototype:
class Solution {
public:
int minDiffInBST(TreeNode* root);
};
|
Here's a description of the tree and what minDiffInBST() should return:
4
/ \
/ \
2 6
/ \
/ \
1 3
Answer: 1 |
1
/ \
/ \
0 48
/ \
/ \
12 49
Answer: 1 |
20
/ \
/ \
10 30
/ \
/ \
1 16
Answer: 4 |
The driver program in Skeleton.cpp reads a Tree on standard input by reading numbers:
UNIX> cat example-1.txt 4 2 6 1 3 UNIX> cat example-2.txt 1 0 48 -1 -1 12 49 # We need two -1's to take the place of the two children of node 3. UNIX> cat example-3.txt 20 10 30 1 16 # Formatting doesn't matter UNIX>
20
rv:4
min:1
max:30
/ \
/ \
10 30
rv:6 rv:-
min:1 min:30
max:16 max:30
/ \
/ \
1 16
rv:- rv:-
min:1 min:16
max:1 max:16
|
I'm going to leave it up to you to figure out how you do this calculation with a postorder traversal, and I'm also going to leave it up to you how to write the program. What I did was define the following method in the Solution class:
void postorder(TreeNode *root, int &rv, int &min, int &max); |
Please feel free to use that method definition to structure your answer.