427.建立四叉树
427.建立四叉树
题解
题目:给一个数组,正方形的,如果其中某部分不是全1或全0,则分成4部分,变成四叉树
思路:递归,其实难点就在于分成四部分
TopLeft: dfs(rowStart, (rowStart+rowEnd)/2, colStart, (colStart+colEnd)/2), TopRight: dfs(rowStart, (rowStart+rowEnd)/2, (colStart+colEnd)/2, colEnd), BottomLeft: dfs((rowStart+rowEnd)/2, rowEnd, colStart, (colStart+colEnd)/2), BottomRight: dfs((rowStart+rowEnd)/2, rowEnd, (colStart+colEnd)/2, colEnd),
代码
type Node struct { Val bool IsLeaf bool TopLeft *Node TopRight *Node BottomLeft *Node BottomRight *Node } func construct(grid [][]int) *Node { var dfs func(rowStart, rowEnd, colStart, colEnd int) *Node dfs = func(rowStart, rowEnd, colStart, colEnd int) *Node { for i := rowStart; i < rowEnd; i++ { for j := colStart; j < colEnd; j++ { if grid[i][j] != grid[rowStart][colStart] { return &Node{ Val: true, IsLeaf: false, TopLeft: dfs(rowStart, (rowStart+rowEnd)/2, colStart, (colStart+colEnd)/2), TopRight: dfs(rowStart, (rowStart+rowEnd)/2, (colStart+colEnd)/2, colEnd), BottomLeft: dfs((rowStart+rowEnd)/2, rowEnd, colStart, (colStart+colEnd)/2), BottomRight: dfs((rowStart+rowEnd)/2, rowEnd, (colStart+colEnd)/2, colEnd), } } } } return &Node{ Val: grid[rowStart][colStart] == 1, IsLeaf: true, TopLeft: nil, TopRight: nil, BottomLeft: nil, BottomRight: nil, } } return dfs(0, len(grid), 0, len(grid)) }