LeetCode Invert Binary Tree 翻转二叉树
题目描述:
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);
}
}
}
还没有评论,来说两句吧...