226. Invert Binary Tree

来源:互联网 发布:最新编程语言发展趋势 编辑:程序博客网 时间:2024/05/04 09:04

采用递归遍历的思想,递归交换左子树,递归交换右子数,最后交换左右孩子,当节点为空时递归结束。代码如下:

/**
 * 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 root;
        TreeNode temp;
        invertTree(root.left);
        invertTree(root.right);
        temp=root.left;
        root.left=root.right;
        root.right=temp;
        return root;
    }
}

0 0
原创粉丝点击