• 2021-04-12:判断二叉树是否是搜索二叉树?


    2021-04-12:判断二叉树是否是搜索二叉树?

    福大大 答案2021-04-12:

    中序遍历有序即可。
    1.递归。
    2.莫里斯遍历。

    代码用golang编写。代码如下:

    package main
    
    import "fmt"
    
    const INT_MAX = int(^uint(0) >> 1)
    const INT_MIN = ^INT_MAX
    
    func main() {
        head := &TreeNode{Val: 5}
        head.Left = &TreeNode{Val: 3}
        head.Right = &TreeNode{Val: 7}
        head.Left.Left = &TreeNode{Val: 2}
        head.Left.Right = &TreeNode{Val: 4}
        head.Right.Left = &TreeNode{Val: 6}
        head.Right.Right = &TreeNode{Val: 8}
        ret := isBST1(head)
        fmt.Println("递归:", ret)
        fmt.Println("----")
        ret = isBST2(head)
        fmt.Println("莫里斯遍历:", ret)
    }
    
    //Definition for a binary tree node.
    type TreeNode struct {
        Val   int
        Left  *TreeNode
        Right *TreeNode
    }
    
    func isBST1(head *TreeNode) bool {
        if head == nil {
            return true
        }
        ansVal := true
        ans := &ansVal
        preVal := INT_MIN
        pre := &preVal
        process(head, pre, ans)
        return *ans
    }
    func process(head *TreeNode, pre *int, ans *bool) {
        if head == nil {
            return
        }
        if *ans {
            process(head.Left, pre, ans)
        }
        if *ans {
            if *pre > head.Val {
                *ans = false
            } else {
                *pre = head.Val
            }
        }
        if *ans {
            process(head.Right, pre, ans)
        }
    }
    
    // 根据morris遍历改写
    func isBST2(head *TreeNode) bool {
        if head == nil {
            return true
        }
        cur := head
        var mostRight *TreeNode
        preVal := INT_MIN
        for cur != nil {
            mostRight = cur.Left
            if mostRight != nil {
                for mostRight.Right != nil && mostRight.Right != cur {
                    mostRight = mostRight.Right
                }
                if mostRight.Right == nil { //先 第一次到达
                    mostRight.Right = cur
                    cur = cur.Left
                    continue
                } else { //后 第二次到达
                    mostRight.Right = nil
                }
            } else { //先 只有一次到达
            }
    
            //此时cur就是中序
            if preVal > cur.Val {
                return false
            } else {
                preVal = cur.Val
            }
    
            //中
            cur = cur.Right
    
        }
        //后
        return true
    }
    

    执行结果如下:
    在这里插入图片描述


    左神java代码
    评论

  • 相关阅读:
    for循环,pydev提示未使用的变量,解决办法
    sc 与net命令的区别
    Selenium测试Ajax程序(转)
    Python yield 使用浅析(转)
    python操作Excel读写--使用xlrd
    Python操作Mysql实例代码教程在线版(查询手册)
    MySQL之alter语句用法总结
    使用WebDriver遇到的那些坑(转)
    python 列表转为字典的两个小方法
    python
  • 原文地址:https://www.cnblogs.com/waitmoon/p/14651036.html
Copyright © 2020-2023  润新知