[leetcode] Binary Tree Upside Down
思路:遞歸實(shí)現(xiàn),注意翻轉(zhuǎn)的規(guī)律,以左子樹作為根,找到左子樹最右邊的節(jié)點(diǎn)作為原有right子樹和根的父節(jié)點(diǎn)。
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; } }

浙公網(wǎng)安備 33010602011771號