leetcode_Invert Binary Tree

描述:

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by  this original tweet  by  Max Howell :
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

思路:

1.记得做树的问题时,有两题类似的,一题是判断二叉树是否镜像对称,另外一题是判断两个二叉树节点的值是否相等,同样都是用递归的方式来做

2.这一题跟镜像对称哪一题类似,从上至下,交换同一个父节点的左右子节点即可。

代码:

public TreeNode invertTree(TreeNode root) {
        if(root==null)
            return root;
        
        if(root.left!=null||root.right!=null)
        {
        	LinkedList<TreeNode> list=new LinkedList<TreeNode>();
        	list.addLast(root);
        	TreeNode curNode=null;
            while(!list.isEmpty())
            {
            	curNode=list.removeFirst();
            	changeTree(curNode);
            	if(curNode.left!=null)
            		list.addLast(curNode.left);
            	if(curNode.right!=null)
            		list.addLast(curNode.right);
            }
        }
        return root;
    }

	public void changeTree(TreeNode root)
	{
		if (root.left != null || root.right != null)
		{
			TreeNode temp = root.left;
			root.left = root.right;
			root.right = temp;
		}
	}


你可能感兴趣的:(LeetCode,tree,binary,invert)