代码随想录二叉树——翻转二叉树

题目

翻转一棵二叉树

//DFS 递归
class Solution {
	public TreeNode invertTree(TreeNode root){
		if(root == null){
			return null;
		}
		invertTree(root.left);
		invertTree(root.right);
		swapChildren(root);
		return root;
	}
	private void swapChildren(TreeNode root){
		TreeNode tmp = root.left;
		root.left = root.right;
		root.right = tmp;
	}
}

//BFS 队列  层序遍历
class Solution {
	public TreeNode invertTree(TreeNode root){
		if(root == null){
			return null;
		}
		ArrayDeque<TreeNode> deque = new ArrayDeque<>();
		deque.offer(root);//添加根节点
		while(! deque.isEmpty()){
			int size = deque.size();//记录当前层节点个数
			while(size-- > 0){
				TreeNode node = deque.poll();//出队列,用node存储
				swap(node);
				if(node.left != null) deque.offer(node.left);
				if(node.right != null) deque.offer(node.right); 
			}
		}
		return root;
	}
	public void swap(TreeNode root){
		TreeNode temp = root.left;
		root.left = root.right;
		root.right = temp;
	}
}

你可能感兴趣的:(代码随想录,java,开发语言)