leetcode深搜专题

// 二叉树的中序非递归遍历 
public static void medOrderUnRecur(Node root) {
        if (root == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        while (!stack.empty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                System.out.print(root.data+" ");
                root = root.right;
            }
        }
        System.out.println();
    }

leetcode 98 验证二叉搜索树

一开始想到二叉搜索树按照中序遍历的话是一个递增序列 只要比较两个顶点的大小,小于的话就返回false,否则往右走,但提交的时候报了错..没搞懂 后面看了下别人的思路,用的是递归版本

double last = -Double.MAX_VALUE;
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (isValidBST(root.left)) {
            if (last < root.val) {
                last = root.val;
                return isValidBST(root.right);
            }
        }
        return false;
    }

下面是非递归版本

 public boolean isValidBST(TreeNode root) {
       if (root == null) {
                return true;
            }
            int preData = Integer.MIN_VALUE;
            Stack<TreeNode> stack = new Stack<>();
            while (root != null || !stack.empty()) {
                if (root != null) {
                    stack.push(root);
                    root = root.left;
                } else {
                    TreeNode node = stack.pop();
                    if (node.val < preData) {
                        return false;
                    } else {
                        preData = node.val;
                    }
                    root = node.right;
                }
            }
            return true;
    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值