lintcode-175-翻转二叉树

175-翻转二叉树

翻转一棵二叉树

样例

挑战

递归固然可行,能否写个非递归的?

标签

二叉树

思路

遍历树,交换每个节点的左右子树

code

/**
 * 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) {
        // write your code here
        if (root == NULL) {
            return;
        }
        queue<TreeNode *> queue;
        queue.push(root);
        while (!queue.empty()) {
            TreeNode * node = queue.front();
            queue.pop();
            if (node->left != NULL) {
                queue.push(node->left);
            }
            if (node->right != NULL) {
                queue.push(node->right);
            }
            swap(node->left, node->right);
        }
    }
};
posted @ 2017-08-03 13:41  LiBaoquan  阅读(229)  评论(0编辑  收藏  举报