找BUG 题目理解 平衡二叉树 定义

https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/

平衡二叉树 定义

 

 是

 

定义错误

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isBalanced(root *TreeNode) bool {
	if root == nil {
		return true
	}
	current := []*TreeNode{root}
	for {
		next := []*TreeNode{}
		n := len(current)
		hasNil := false
		for i := 0; i < n; i++ {
			t := current[i]
			if t != nil {
				if t.Left == nil {
					hasNil = true
				} else {
					next = append(next, t.Left)
				}
				if t.Right == nil {
					hasNil = true
				} else {
					next = append(next, t.Right)
				}
			}
		}
		m := len(next)
		if m == 0 {
			break
		}
		for i := 0; i < m; i++ {
			t := next[i]
			if t != nil {
				if (t.Left != nil || t.Right != nil) && hasNil {
					return false
				}
			}
		}
		current = next
	}
	return true
}

  

package main

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isBalanced(root *TreeNode) bool {
	if root == nil {
		return true
	}
	fn := func(root *TreeNode) int {
		if root == nil {
			return 0
		}
		c := 1
		current := []*TreeNode{root}
		for {
			next := []*TreeNode{}
			n := len(current)
			for i := 0; i < n; i++ {
				t := current[i]
				if t != nil {
					if t.Left != nil {
						next = append(next, t.Left)
					}
					if t.Right != nil {
						next = append(next, t.Right)
					}
				}
			}
			m := len(next)
			if m == 0 {
				break
			}
			c++
			current = next
		}
		return c
	}

	return fn(root.Left)-fn(root.Right) == 1 || fn(root.Left)-fn(root.Right) == -1 || fn(root.Left)-fn(root.Right) == 0
}

  

修正

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isBalanced(root *TreeNode) bool {
	if root == nil {
		return true
	}
	fn := func(root *TreeNode) int {
		if root == nil {
			return 0
		}
		c := 1
		current := []*TreeNode{root}
		for {
			next := []*TreeNode{}
			n := len(current)
			for i := 0; i < n; i++ {
				t := current[i]
				if t != nil {
					if t.Left != nil {
						next = append(next, t.Left)
					}
					if t.Right != nil {
						next = append(next, t.Right)
					}
				}
			}
			m := len(next)
			if m == 0 {
				break
			}
			c++
			current = next
		}
		return c
	}

	current := []*TreeNode{root}
	for {
		next := []*TreeNode{}
		n := len(current)
		for i := 0; i < n; i++ {
			t := current[i]
			if t != nil {
				if t.Left != nil {
					next = append(next, t.Left)
				}
				if t.Right != nil {
					next = append(next, t.Right)
				}
			}
			root := t
			b := fn(root.Left)-fn(root.Right) == 1 || fn(root.Left)-fn(root.Right) == -1 || fn(root.Left)-fn(root.Right) == 0
			if !b {
				return false
			}
		}
		m := len(next)
		if m == 0 {
			break
		}
		current = next
	}

	return true
}

  

 

posted @ 2022-04-26 23:12  papering  阅读(37)  评论(0编辑  收藏  举报