實現一個函數,檢查一棵二叉樹是否爲二叉搜索樹。
示例 1:
輸入:
2
/ \
1 3
輸出: true
示例 2:
輸入:
5
/ \
1 4
/ \
3 6
輸出: false
解釋: 輸入爲: [5,1,4,null,null,3,6]。
根節點的值爲 5 ,但是其右子節點值爲 4 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/legal-binary-search-tree-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
中序遍歷,判斷大小。
func isValidBST(root *TreeNode) bool {
if root == nil || (root.Left == nil && root.Right == nil) {
return true
}
flag := true
last := make([]int,0)
run(root,&last,&flag)
return flag
}
func run(root *TreeNode,last *[]int,flag *bool) {
if *flag == false {
return
}
if root == nil {
return
}
run(root.Left,last,flag)
if len(*last) == 0 {
*last = append(*last,root.Val)
} else {
if root.Val <= (*last)[len(*last)-1] {
*flag = false
return
} else {
*last = append(*last,root.Val)
}
}
run(root.Right,last,flag)
}