标签:offer 思路 node etc tree 递归 binary 非递归 public
Invert a binary tree.
比如原来的树为 0 1 2
逆转后的树为 0 2 1
也就是把所有结点的左右结点互换
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
TreeNode tmp = invertTree(root.right);
root.right = invertTree(root.left);
root.left = tmp;
return root;
}
}
非递归,用树的层次遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode tmp = queue.poll();
TreeNode left = tmp.left;
tmp.left = tmp.right;
tmp.right = left;
if(tmp.left != null) queue.offer(tmp.left);
if(tmp.right != null) queue.offer(tmp.right);
}
return root;
}
}
[leetcode]226.Invert Binary Tree
标签:offer 思路 node etc tree 递归 binary 非递归 public
原文地址:https://www.cnblogs.com/shinjia/p/9785534.html