Leetcode 226. Invert Binary Tree

twisted-fate發表於2019-05-24

利用層序遍歷 , 也就是佇列

虛擬碼:

make a queue
push root into queue
if queue is not empty
    node= queue pop
    if has left 
        if left has child
            enqueue left
    if has right
        if right has child
            enqueue right

    tmp = node.left
    node.left=node.right
    node.right=tmp

結果:

func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return root
    }
    queue := []*TreeNode{}
    queue = append(queue, root)

    for len(queue) != 0 {
        node := queue[0]
        queue = queue[1:]

        if node.Left != nil {
            if node.Left.Left != nil || node.Left.Right != nil {
                queue = append(queue, node.Left)
            }
        }
        if node.Right != nil {
            if node.Right.Left != nil || node.Right.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        tmp := node.Left
        node.Left = node.Right
        node.Right = tmp
    }
    return root
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章