LeetCode-226.Invert Binary Tree

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1
public TreeNode invertTree(TreeNode root) {//树 递归 my
        if (null!=root){
            TreeNode left = invertTree(root.left);
            TreeNode right = invertTree(root.right);
            root.left=right;
            root.right=left;
        }
        return root;
    }  

 

非递归的方法

public TreeNode invertTree(TreeNode root) {
    if (root == null) return null;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    while (!queue.isEmpty()) {
        TreeNode current = queue.poll();
        TreeNode temp = current.left;
        current.left = current.right;
        current.right = temp;
        if (current.left != null) queue.add(current.left);
        if (current.right != null) queue.add(current.right);
    }
    return root;
}

  

  

posted @ 2019-02-25 15:10  月半榨菜  阅读(103)  评论(0编辑  收藏  举报