跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:226.翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:
输入:root = [2,1,3]
输出:[2,3,1]
示例 3:
输入:root = []
输出:[]
递归法,类似前序遍历
public TreeNode invertTree(TreeNode root) {if(root == null) return root;swapTreeNode(root);invertTree(root.left);invertTree(root.right);return root;}private void swapTreeNode(TreeNode node){TreeNode temp = node.left;node.left = node.right;node.right = temp;}
递归法,类似后序遍历
public TreeNode invertTree(TreeNode root) {if(root == null) return root;invertTree(root.left);invertTree(root.right);swapTreeNode(root);return root;}private void swapTreeNode(TreeNode node){TreeNode temp = node.left;node.left = node.right;node.right = temp;}
递归法,类似中序遍历
public TreeNode invertTree(TreeNode root) {if(root == null) return root;invertTree(root.left);swapTreeNode(root);invertTree(root.left);return root;}private void swapTreeNode(TreeNode node){TreeNode temp = node.left;node.left = node.right;node.right = temp;}