题目
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
思路
- 递归
先把左右子树各自都翻转了,再将左右子树互换位置。 - 迭代
层序遍历思路。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//(1)递归
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
//递归翻转root左子树
TreeNode leftNode = invertTree(root.left);
//递归翻转root右子树
TreeNode rightNode = invertTree(root.right);
//交换root的左右子树
root.left = rightNode;
root.right = leftNode;
return root;
}
//(2)迭代,层序遍历的思路
public TreeNode invertTree1(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;
}
}
网友评论