Skip to content

Latest commit

 

History

History
75 lines (57 loc) · 956 Bytes

226.翻转二叉树.md

File metadata and controls

75 lines (57 loc) · 956 Bytes

226. 翻转二叉树

url

题目

翻转一棵二叉树。

示例

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

输出

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

方法

递归

code

js

let invertTree = root => {
    if (root == null) return null;
    let left = root.left;
    root.left = invertTree(root.right);
    root.right = invertTree(left);
    return root;
};

go

func invertTree(root *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}
	left := root.Left
	root.Left = invertTree(root.Right)
	root.Right = invertTree(left)
	return root
}

java

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode left = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(left);
        return root;
    }
}