Invert a binary tree

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

想法

  需要使用遞迴,不能單純的只是交換左右的值,而是要交換左右整棵樹。

code

struct TreeNode* invertTree(struct TreeNode* root) {
    if(!root||(!root->right && !root->left))
        return root;
    struct TreeNode* tmp;
    tmp = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(tmp);
    return root;
}

arrow
arrow
    文章標籤
    LeetCode C
    全站熱搜

    Davis 發表在 痞客邦 留言(0) 人氣()