Invert Binary Tree

xiaoxiao2021-02-27  527

Invert Binary Tree

迭代版本:

` public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) {val = x;} } public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()) { TreeNode t = queue.poll(); TreeNode right = t.right; t.right = t.left; t.left = right; if (t.left != null) queue.offer(t.left); if (t.right != null) queue.offer(t.right); } return root; } } `

递归版本:

` public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode r = root.right; root.right = invertTree(root.left); root.left = invertTree(r); return root; } } `
转载请注明原文地址: https://www.6miu.com/read-2608.html

最新回复(0)