题目描述:同点击打开链接
Invert a binary tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
思路一:递归DFS
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) return root;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if (root.left != null)
root.left = invertTree(root.left);
if (root.right != null)
root.right = invertTree(root.right);
return root;
}
}
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) return root;
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
}
思路二:用栈,DFS
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) return root;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty())
{
TreeNode node = stack.pop();
if (node.left != null || node.right != null)
{
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
}
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
return root;
}
}
思路三:用队列,BFS
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) return root;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty())
{
TreeNode node = queue.poll();
if (node.left != null || node.right != null)
{
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
}
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
return root;
}
}