反转二叉树

来源:互联网 发布:JavaScript字符串分割 编辑:程序博客网 时间:2024/05/22 07:57

题目:Invert Binary Tree

描述:

invert 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; } * } */public class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null)            return root;        TreeNode node = root.left;        root.left = root.right;        root.right = node;        invertTree(root.left);        invertTree(root.right);        return root;    }}

算法解释

运用二叉树的广度遍历,将每个节点的左子节点和右子节点调换

运行效率:

运行效率

0 0
原创粉丝点击