标签:经验 规律 levels height san bin row null 通过
Invert a binary tree.
4 / 2 7 / \ / 1 3 6 9to
4 / 7 2 / \ / 9 6 3 1翻转二叉树,本题属于容易题题目容易理解,可以通过层次遍历方法进行反转,类似【637. Average of Levels in Binary Tree】题目,
class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return null; Queue<TreeNode> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()) { TreeNode tmp= null; TreeNode t= q.poll(); tmp = t.left; t.left = t.right; t.right = tmp; if(t.left != null) q.add(t.left); if(t.right != null) q.add(t.right); } return root; } }
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode right = invertTree(root.right); TreeNode left = invertTree(root.left); root.left = right; root.right = left; return root; }
标签:经验 规律 levels height san bin row null 通过
原文地址:http://www.cnblogs.com/wxshi/p/7598538.html