前言
继续继续算法第二篇
题目
- 简单描述:
反转二叉树
问题详情
Invert Binary Tree.
解法:
1. 解法一 递归
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 treeNode = root.left;
root.left = root.right;
root.right = treeNode;
return root;
}
2. 解法二 非递归(经典解法)
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
}
return root;
}
总结
算法贵在持之以恒,做多了 就懂了!继续干小伙伴们!!!
网友评论