leetcode树1-4

leetcode树

1.遍历二叉树(前序,中序,后序)

img

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

//前序:ABDFGHIEC
func readPreDepth(root *TreeNode) {
	if root != nil {
		fmt.Println(root.Val)
		readPreDepth(root.Left)
		readPreDepth(root.Right)
	}
}

//中序:FDHGIBEAC
func readInDepth(root *TreeNode) {
	if root != nil {
		readInDepth(root.Left)
		fmt.Println(root.Val)
		readInDepth(root.Right)
	}
}

//后序:FHIGDEBCA
func readAfterDepth(root *TreeNode) {
	if root != nil {
		readPreDepth(root.Left)
		readPreDepth(root.Right)
		fmt.Println(root.Val)
	}
}

2.二叉树的最大深度

题目:二叉树的最大深度
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

答案:

//递归,https://www.bilibili.com/video/BV1Hb4y1E7r6/?spm_id_from=333.788&vd_source=6728716b092fdb6cc9a0ef2071c804ed
func maxDepth(root *TreeNode) int {
	if root == nil {
		//没有节点了就是0
		return 0
	}
	//1代表有节点,还要加上他的左节点和右节点的最大深度
	return 1+ max(maxDepth(root.Left), maxDepth(root.Right))
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}


func main() {
	three := TreeNode{Val: 3}
	nine := TreeNode{Val: 9}
	twenty := TreeNode{Val: 20}
	seven := TreeNode{Val: 7}
	fifteen := TreeNode{Val: 15}

	three.Left = &nine
	three.Right = &twenty
	twenty.Left = &fifteen
	twenty.Right = &seven

	fmt.Println(maxDepth(&three))

}

3.验证二叉搜索树

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

答案:

//https://leetcode.cn/problems/validate-binary-search-tree/solution/yan-zheng-er-cha-sou-suo-shu-by-leetcode-solution/
func isValidBST(root *TreeNode) bool {
    stack := []*TreeNode{}
    inorder := math.MinInt64
    for len(stack) > 0 || root != nil {
        for root != nil {
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if root.Val <= inorder {
            return false
        }
        inorder = root.Val
        root = root.Right
    }
    return true
}

4.对称二叉树

题目:对称二叉树

示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true

答案:

func isSymmetric(root *TreeNode) bool {
	return check(root, root)
}


/*
递归思路:
如果一个树的左子树与右子树镜像对称,那么这个树是对称的。
我们可以实现这样一个递归函数,通过「同步移动」两个指针的方法来遍历这棵树,l指针和r指针一开始都指向这棵树的根,随后r右移时,l左移,l左移时,r右移。每次检查当前l和r节点的值是否相等,如果相等再判断左右子树是否对称。
*/
func check(p, q *TreeNode) bool {
	if p == nil && q == nil {
		return true
	}
	if p == nil || q == nil {
		return false
	}
	return p.Val == q.Val && check(p.Left, q.Right) && check(p.Right, q.Left)
}
posted @ 2022-10-09 17:18  Jeff的技术栈  阅读(23)  评论(0编辑  收藏  举报
回顶部