LintCode 175. Invert Binary Tree

  1. Invert Binary Tree
    中文English
    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:递归。
代码如下。

/**
 * 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;
    }
};

解法2:非递归版本。
TBD

上一篇:Sentinel 控制台集成 nacos


下一篇:EJB包括(SessionBean,EntityBean)说出他们的生命周期,及如何管理事务的?