反转二叉树
4
/
2 7
/ \ /
1 3 6 9
Output:
4
/
7 2
/ \ /
9 6 3
对左右进行一个反转情况
递归做法
还是套路做法
- 对左边节点进行函数操作
- 对右边节点进行函数操作
- swap 对调做法, root.left , root.right
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null || (root.right==null && root.left==null))
return root;
TreeNode left = invertTree(root.left);
TreeNode right= invertTree(root.right);
TreeNode tmp= left;
root.left= right;
root.right= left;
return root;
}
}
递归使用大量的stack ,应该着重避免使用stack
另一方面其实也可以采用下面这种方法
写法可能更好点
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
//默认左边的处理成功了的情况
invertTree(root.left);
// 默认右边成功的情况
invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
DFS 深度优先搜索
使用stack
dequeu.push(头结点情况)
while(队列不为空){
具体操作代码逻辑,先处理根结点
判断左边节点是否为空
不为空,入队列
判断右边节点是否为空
不为空, 入队列
}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
TreeNode left = node.left;
node.left = node.right;
node.right = left;
// 注意在这里处理左右节点的顺序是无所谓的情况
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return root;
}
}
使用层次遍历的思想
主要是利用队列, 先进入先出来的思想
关于Java 中Deque 接口的使用可以参考一下的链接, 使用队里的情况
先进入的先处理的的基本情况
层次遍历的代码
- 根节点先入队列, 在尾巴加入
- while(队列不为空)
- 出根节点(先进先出)
- 处理步骤三中的处理的节点,完成该过程的判断(主要的逻辑判断情况)
- 判断是否有左边节点情况, 加入队列
- 判断对否有右边节点情况, 加入队列
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
final TreeNode node = queue.poll();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}