java inverse binary tree algorithm

Title: Invert a binary tree.

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

to

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

Here is the algorithm I gave:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        if(root.left!=null){
            invertTree(root.left);
        }
        if(root.right!=null){
            invertTree(root.right);
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325336978&siteId=291194637