classSolution{public:intgetMinimumDifference(TreeNode*root){// very similar to 94. Binary Tree Inorder Traversalintans=INT_MAX;intprev=-1;stack<TreeNode*>stack;while(root||!stack.empty()){while(root){stack.push(root);root=root->left;}root=stack.top(),stack.pop();if(prev>=0)ans=min(ans,root->val-prev);prev=root->val;root=root->right;}returnans;}};
JAVA
classSolution{publicintgetMinimumDifference(TreeNoderoot){// very similar to 94. Binary Tree Inorder Traversalintans=Integer.MAX_VALUE;intprev=-1;Deque<TreeNode>stack=newArrayDeque<>();while(root!=null||!stack.isEmpty()){while(root!=null){stack.push(root);root=root.left;}root=stack.pop();if(prev>=0)ans=Math.min(ans,root.val-prev);prev=root.val;root=root.right;}returnans;}}
Login to Codeflu
Log in to stay update and get notify on new arrivals.