您的位置:首页 > 其它

LeetCode Invert Binary Tree 翻转二叉树

2017-09-13 10:24 357 查看
题目描述:

Invert a binary tree.

样例输入输出:

1         1
/ \       / \
2   3  => 3   2
/       \
4         4


解法一:

递归实现

private void invertRecursion(TreeNode root) {
if (root == null) {
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if (root.left != null) {
invertRecursion(root.left);
}
if (root.right != null) {
invertRecursion(root.right);
}
}


解法二:

非递归实现 使用辅助空间

private void invertLoop(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
TreeNode tmp = stack.pop();
//交换左右子树
TreeNode l = tmp.left;
tmp.left = tmp.right;
tmp.right = l;
if (tmp.right != null) {
stack.push(tmp.right);
}
if (tmp.left != null) {
stack.push(tmp.left);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: