【代码随想录——二叉树二周目】

1.对称二叉树

在这里插入图片描述
思路:

  • 递归法,从根节点开始,向两边扩散,遍历的顺序是相反的
  • 迭代法,可以层次遍历,

1.1 递归法

func isSymmetric(root *TreeNode) bool {
    if root==nil{
        return true
    }
    return compare(root.Left,root.Right)
}

func compare(node1 *TreeNode,node2 *TreeNode) bool{
    if node1==nil && node2==nil{
        return true
    }
    if node1==nil || node2==nil{
        return false
    }
    if node1.Val!=node2.Val{
        return false
    }
    inside := compare(node1.Right,node2.Left)
    outside := compare(node1.Left,node2.Right)
    return inside && outside
}

1.2 迭代法

func isSymmetric(root *TreeNode) bool {
	if root==nil{
		return true
	}
	var queue []*TreeNode
	queue = append(queue,root.Left,root.Right)
	for len(queue)>0{
		left := queue[0]
		right := queue[1]
        queue = queue[2:]
		if left==nil && right==nil {
			continue
		}
		if left==nil || right==nil || (left.Val!=right.Val){
			return false
		}
		queue = append(queue,left.Right,right.Left,left.Left,right.Right)

	}
	return true
}

1.3 相同的树

在这里插入图片描述
采用递归的方法较为简单:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSameTree(p *TreeNode, q *TreeNode) bool {
    return isSame(p,q)
}

func isSame(node1 *TreeNode,node2 *TreeNode) bool {
    if node1==nil && node2==nil{
        return true
    }

    if node1==nil || node2==nil || node1.Val!=node2.Val{
        return false
    }

    return isSame(node1.Left,node2.Left) && isSame(node1.Right,node2.Right)
}

1.4 另一棵树的子树

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
    if root==nil{
        return false
    }
    if isSameTree(root, subRoot) {
		return true
	}
    return isSubtree(root.Left, subRoot) || isSubtree(root.Right,subRoot)
}

func isSameTree(s,t *TreeNode)bool{
    if s==nil && t==nil{
        return true
    }
    if s==nil || t==nil {
        return false
    }
    return s.Val==t.Val && isSameTree(s.Left,t.Left) && isSameTree(s.Right,t.Right)
}

2.二叉树的最大深度

2.1 层次遍历

func maxDepth(root *TreeNode) int {
	ans := 0
    if root == nil{
        return 0
    }
    queue := list.New()
    queue.PushBack(root)
    for queue.Len() > 0 {
        length := queue.Len()
        for i := 0; i < length; i++ {
            node := queue.Remove(queue.Front()).(*TreeNode)
            if node.Left != nil {
                queue.PushBack(node.Left)
            }
            if node.Right != nil {
                queue.PushBack(node.Right)
            }
        }
        ans++//记录深度,其他的是层序遍历的板子
    }
    return ans
}

2.2 递归法

func maxDepth(root *TreeNode) int {
	if root==nil{
		return 0
	}
	return 1+maxNum(maxDepth(root.Left),maxDepth(root.Right))
}

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

2.3 N叉树的最大深度

只能使用层次遍历法。

func maxDepth(root *Node) int {
	if root == nil {
		return 0
	}
	var queue []*Node
	queue = append(queue,root.Children...)
	ans := 1
	for len(queue)>0{
        ans++
		length := len(queue)
		for i:=0;i<length;i++{
			queue = append(queue,queue[i].Children...)
		}
		queue = queue[length:]
	}
	return ans
}

3.二叉树的最小深度

3.1 层次遍历

func minDepth(root *TreeNode) int {
	li := make([]*TreeNode, 0)
	tmp := make([]*TreeNode, 0)
	ans := 0
	if root == nil {
		return ans
	}
	li = append(li, root)
	for len(li) > 0 {
		length := len(li)
		ans++
		for i := 0; i < length; i++ {
			if li[i].Left == nil && li[i].Right == nil {
				return ans
			}
			if li[i].Left != nil {
				tmp = append(tmp, li[i].Left)
			}
			if li[i].Right != nil {
				tmp = append(tmp, li[i].Right)
			}
		}
		li = tmp
		tmp = nil
	}
	return ans
}

3.2 递归算法

func minDepth(root *TreeNode) int {
    if root==nil{
        return 0
    }
    if root.Left==nil && root.Right!=nil{
        return 1+minDepth(root.Right)
    }
    if root.Left!=nil && root.Right==nil{
        return 1+minDepth(root.Left)
    }
    return 1+minNum(minDepth(root.Left),minDepth(root.Right))
}

func minNum(a,b int) int{
    if a<b{
        return a
    }
    return b
}

4.完全二叉树的节点个数

4.1 层次遍历法

func countNodes(root *TreeNode) int {
	ans := 0
	if root == nil {
		return ans
	}
	var arr []*TreeNode
	arr = append(arr,root)
	ans++
	for len(arr)>0{
		length := len(arr)
		for index:=length-1;index>=0;index--{
			if arr[index].Left!=nil{
				ans++
				arr = append(arr,arr[index].Left)
			}
			if arr[index].Right!=nil{
				ans++
				arr = append(arr,arr[index].Right)
			}
		}
		arr = arr[length:]
	}
	return ans
}

4.2 递归版本

//本题直接就是求有多少个节点,无脑存进结果变量就行了。
func countNodes(root *TreeNode) int {
    if root == nil {
        return 0
    }
    res := 1
    if root.Right != nil {
        res += countNodes(root.Right)
    }
    if root.Left != nil {
        res += countNodes(root.Left)
    }
    return res
}

5.平衡二叉树

5.1递归

在计算各个节点高度的同时判断是否是是否是平衡树。

func isBalanced(root *TreeNode) bool {
    h := getHeight(root)
    if h == -1 {
        return false
    }
    return true
}

func getHeight(root *TreeNode)int{
    if root==nil{
        return 0
    }
    l, r := getHeight(root.Left), getHeight(root.Right)
    if l==-1 || r==-1{
        return -1
    }
    
    if l - r > 1 || r - l > 1 {
        return -1
    }

    return max(l, r) + 1
}

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

6.二叉树的所有路径

6.1 递归法

递归终止的条件是:左右两个子节点都为空的时候,则记录这一条路径。

func binaryTreePaths(root *TreeNode) []string {
	ans := make([]string, 0)
	if root == nil {
		return ans
	}

	findPath(root, "", &ans)
	return ans
}

func findPath(node *TreeNode, temp string, ans *[]string) {
	if node.Left == nil && node.Right == nil {
		temp = temp + strconv.Itoa(node.Val)
		*ans = append(*ans, temp)
	}
	temp = temp + strconv.Itoa(node.Val)+ "->"
	if node.Left != nil {
		findPath(node.Left, temp, ans)
	}
	if node.Right != nil {
		findPath(node.Right, temp, ans)
	}
}
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值