LintCode 175. Invert Binary Tree

  1. Invert Binary Tree
Description
Invert a binary tree.Left and right subtrees exchange.

Example
Example 1:

Input: {1,3,#}
Output: {1,#,3}
Explanation:
	  1    1
	 /  =>  \
	3        3
Example 2:

Input: {1,2,3,#,#,4}
Output: {1,3,2,#,4}
Explanation: 
	
      1         1
     / \       / \
    2   3  => 3   2
       /       \
      4         4
Challenge
Do it in recursion is acceptable, can you do it without recursion?

解法1:递归。注意跟 LintCode 1360 Symmetric Tree 这题区分。这个是DFS的方法。
这个总结得很好。
https://labuladong.gitee.io/algo/di-yi-zhan-da78c/shou-ba-sh-66994/dong-ge-da-cbce8/
代码如下。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    void invertBinaryTree(TreeNode * root) {
        if (!root) return;
        
        helper(root);
        
        return;
    }

private:
    TreeNode * helper(TreeNode * root) {
        if (!root) return NULL;

        TreeNode * origRight = root->right;
        root->right = helper(root->left);
        root->left = helper(origRight);
        
        return root;
    }
};

也可以

  TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        TreeNode * rootLeft = root->left;   //change this line
        root->left = invertTree(root->right);
        root->right = invertTree(rootLeft);
        return root;
    }

下面的做法更简单:这个是遍历的方法。注意swap的位置可以是preorder或postorder,但不能是inorder。

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

解法2:非递归版本。
TBD

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值