[leetcode] 226. Invert Binary Tree 解题报告
本题目可以采用三种方法Straightforward DFS recursive, iterative, BFS solutions
1.深度优先 递归
2.迭代
3.广度优先
a.要弄懂final关键字的含义
此题不加也行
class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return null; final TreeNode left=root.left, right=root.right; root.left=invertTree(right); root.right=invertTree(left);
return root; } }
b.迭代
public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while(!stack.isEmpty()) { final TreeNode node = stack.pop(); final 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; } }
c.广度优先
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; } }