ð 226. 翻蜬äºåæ
2022幎6æ9æ¥
- algorithm
ð 226. 翻蜬äºåæ
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1 - éåœ
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// æè·¯ïŒ
// éåœ
return mySol(root);
}
private TreeNode mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return root;
}
// root != null
TreeNode left = mySol(root.left);
TreeNode right = mySol(root.right);
// 亀æ¢å·Šå³èç¹
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
return root;
}
}
èŸåº 1
è§£æ³ 2 - è¿ä»£
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// æè·¯ïŒ
// è¿ä»£ - åå©èŸ
å©æ
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null) {
return root;
}
stack.push(root);
while(!stack.isEmpty()) {
TreeNode cur = stack.pop(); // èŠç¿»èœ¬çäºåæ èç¹
swap(cur);
if(cur.left != null) {
stack.push(cur.left);
}
if(cur.right != null) {
stack.push(cur.right);
}
}
return root;
}
private void swap(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}