LeetCode(226):翻转二叉树
开头
最近一直再刷树方面的题目,希望尽早掌握!
题意
题解
一、层次遍历,从上向下翻转
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
//队列实现广度优先遍历
TreeNode result = root;
if(root == null){
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(result);
while(!queue.isEmpty()){
TreeNode temp = queue.poll();
TreeNode t1 = temp.left;
TreeNode t2 = temp.right;
temp.right = t1;
temp.left = t2;
if(t1!=null){
queue.offer(t1);
}
if(t2!=null){
queue.offer(t2);
}
}
return result;
}
}
二、递归,从下向上遍历翻转
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
//递归实现深度优先遍历
if(root == null){
return root;
}
TreeNode l = invertTree(root.left);
TreeNode r = invertTree(root.right);
root.left = r;
root.right = l;
return root;
}
}