[leetcode] Binary Tree Upside Down
思路:递归实现,注意翻转的规律,以左子树作为根,找到左子树最右边的节点作为原有right子树和根的父节点。
class Solution { public TreeNode upsideDownBinaryTree(TreeNode root) { if (root ==null || root.left ==null && root.right ==null) return root; TreeNode left = upsideDownBinaryTree(root.left); TreeNode right = upsideDownBinaryTree(root.right); TreeNode leftRightest = left; while(leftRightest.right != null){ leftRightest = leftRightest.right; } leftRightest.left = right; leftRightest.right = root; root.left = null; root.right = null; return left; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步