美文网首页
LeetCode 226. Invert Binary Tree

LeetCode 226. Invert Binary Tree

作者: 关玮琳linSir | 来源:发表于2017-10-27 17:23 被阅读45次

Invert a binary tree.

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

to

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

题意:逆转一颗二叉树

代码

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

相关文章

网友评论

      本文标题:LeetCode 226. Invert Binary Tree

      本文链接:https://www.haomeiwen.com/subject/kyldpxtx.html