Mirror image of a binary tree

前端 未结 13 2408
时光取名叫无心
时光取名叫无心 2020-12-01 09:00

Suppose there is a tree:

             1
            / \\
           2   3
              / \\
             4   5

Then the mirror image will

相关标签:
13条回答
  • 2020-12-01 09:27

    An iterative solution:

    public void mirrorIterative() {
        Queue<TreeNode> nodeQ = new LinkedList<TreeNode>();
        nodeQ.add(root);
        while(!nodeQ.isEmpty()) {
            TreeNode node = nodeQ.remove();
            if(node.leftChild == null && node.rightChild == null)
                continue;
            if(node.leftChild != null && node.rightChild != null) {
                TreeNode temp = node.leftChild;
                node.leftChild = node.rightChild;
                node.rightChild = temp;
                nodeQ.add(node.leftChild);
                nodeQ.add(node.rightChild);
            }
            else if(node.leftChild == null) {
                node.leftChild = node.rightChild;
                node.rightChild = null;
                nodeQ.add(node.leftChild);
            } else {
                node.rightChild = node.leftChild;
                node.leftChild = null;
                nodeQ.add(node.rightChild);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题