LeetCode-226:Invert Binary Tree

来源:互联网 发布:linux安装yum 编辑:程序博客网 时间:2024/06/11 00:25

原题描述如下:

Invert a binary tree.

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

题意给定一个二叉树,将该树左右反转,

解题思路:先判断根节点是否为空,为空直接返回null,在将左右子节点对换,然后采用递归方式对左右节点进行反转

Java代码:

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        
        TreeNode left = root.left;
        
        root.left = root.right;
        root.right = left;
        
        invertTree(root.left);
        invertTree(root.right);
        
        return root;
    }
}
0 0
原创粉丝点击