zoukankan      html  css  js  c++  java
  • 175 翻转二叉树

    原题网址:https://www.lintcode.com/problem/invert-binary-tree/description

    描述

    翻转一棵二叉树

    您在真实的面试中是否遇到过这个题?  

    样例

      1         1
     /        / 
    2   3  => 3   2
       /       
      4         4

    挑战

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

    标签
    二叉树
     
    递归思路:二叉树相关的问题用递归解决是相对容易理解的,尽管我对递归很懵比……递归,问题要么在递去过程中解决,要么在归来过程中解决。这道题是翻转二叉树,从远离根的末梢开始,先翻转左右孩子均是叶子结点(包括NULL)的父节点,再向上返回翻转以该父节点为左(右)孩子的祖父结点……以此类推。可以看出,问题是在归来过程中解决的。
    PS:本题还可以在递去过程中解决,先翻转上面的一层,再翻转下面的,从上到下。即把交换语句块放到递归语句块前面。
    AC代码:
    /**
     * 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 ;
        }
        
        invertBinaryTree(root->left);
        invertBinaryTree(root->right);
        
        TreeNode *temp=root->right;
        root->right=root->left;
        root->left=temp;
        }
    };

     

    非递归:广度优先搜索。从根开始一层层遍历,交换结点的左右孩子。

     
    AC代码:
    /**
     * 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 *> tmp;
        tmp.push(root);
        while(!tmp.empty())
        {
            TreeNode *p=tmp.front();
            tmp.pop();
            swap(p->left,p->right);
            if (p->left!=NULL)
            {
                tmp.push(p->left);
            }
            if (p->right!=NULL)
            {
                tmp.push(p->right);
            }
        }
        }
    };

     

     
     
     
  • 相关阅读:
    前端经典书籍
    D3基本概念
    Array.map和parseInt的用法
    首屏和白屏时间计算
    css换肤总结
    文件上传总结
    js的uuid
    html5 drag事件用法
    shell脚本中的逻辑判断 文件目录属性判断 if特殊用法 case判断
    Mac vim“装逼”配置
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9175104.html
Copyright © 2011-2022 走看看