LeetCode 226 (Invert Binary Tree
2019-05-25 本文已影响0人
Lcap
LeetCode:226 invert-binary-tree
先序遍历:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
if(root.left != null)
invertTree(root.left);
if(root.right != null)
invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
中序遍历:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
if(root.left != null)
invertTree(root.left);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
0if(root.right != null)
invertTree(root.right);
return root;
}
}
后序遍历:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
if(root.left != null)
invertTree(root.left);
if(root.right != null)
invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
层序遍历:
class Solution {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> list = new LinkedList<>();
if(root == null)
return null;
list.add(root);
while(!list.isEmpty()) {
TreeNode node = list.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if(node.left != null)
list.add(node.left);
if(node.right != null)
list.add(node.right);
}
return root;
}
}