mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
修改0530.二叉搜索树的最小绝对差.md的Java版本 进行了代码格式化并添加了统一迭代法的注释
This commit is contained in:
@ -155,13 +155,17 @@ public:
|
|||||||
class Solution {
|
class Solution {
|
||||||
TreeNode pre; // 记录上一个遍历的结点
|
TreeNode pre; // 记录上一个遍历的结点
|
||||||
int result = Integer.MAX_VALUE;
|
int result = Integer.MAX_VALUE;
|
||||||
|
|
||||||
public int getMinimumDifference(TreeNode root) {
|
public int getMinimumDifference(TreeNode root) {
|
||||||
if(root==null)return 0;
|
if (root == null)
|
||||||
|
return 0;
|
||||||
traversal(root);
|
traversal(root);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void traversal(TreeNode root) {
|
public void traversal(TreeNode root) {
|
||||||
if(root==null)return;
|
if (root == null)
|
||||||
|
return;
|
||||||
// 左
|
// 左
|
||||||
traversal(root.left);
|
traversal(root.left);
|
||||||
// 中
|
// 中
|
||||||
@ -184,17 +188,22 @@ class Solution {
|
|||||||
|
|
||||||
if (root != null)
|
if (root != null)
|
||||||
stack.add(root);
|
stack.add(root);
|
||||||
|
|
||||||
|
// 中序遍历(左中右),由于栈先入后出,反序(右中左)
|
||||||
while (!stack.isEmpty()) {
|
while (!stack.isEmpty()) {
|
||||||
TreeNode curr = stack.peek();
|
TreeNode curr = stack.peek();
|
||||||
if (curr != null) {
|
if (curr != null) {
|
||||||
stack.pop();
|
stack.pop();
|
||||||
|
// 右
|
||||||
if (curr.right != null)
|
if (curr.right != null)
|
||||||
stack.add(curr.right);
|
stack.add(curr.right);
|
||||||
|
// 中(先用null标记)
|
||||||
stack.add(curr);
|
stack.add(curr);
|
||||||
stack.add(null);
|
stack.add(null);
|
||||||
|
// 左
|
||||||
if (curr.left != null)
|
if (curr.left != null)
|
||||||
stack.add(curr.left);
|
stack.add(curr.left);
|
||||||
}else{
|
} else { // 中(遇到null再处理)
|
||||||
stack.pop();
|
stack.pop();
|
||||||
TreeNode temp = stack.pop();
|
TreeNode temp = stack.pop();
|
||||||
if (pre != null)
|
if (pre != null)
|
||||||
@ -674,3 +683,4 @@ public class Solution
|
|||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user