心得:
這題也是典型的遞迴,題目要求把二元樹整個翻轉過來。
問題:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
答案:
- 遞迴
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode InvertTree(TreeNode root) { if(root == null){ return null; } var left = root.left; var right = root.right; root.left = InvertTree(right); root.right = InvertTree(left); return root; } }