zoukankan      html  css  js  c++  java
  • 剑指offer纪念版 何海涛著 部分纠正

    类似的再举一个例子:

    题目:从上往下打印二叉树,何老师的代码如下(是没有问题的):

    void PrintFromTopToBottom(BinaryTreeNode* pRoot)
    {
        if(pRoot == nullptr)
            return;
    
        std::deque<BinaryTreeNode *> dequeTreeNode;
    
        dequeTreeNode.push_back(pRoot);
    
        while(dequeTreeNode.size())
        {
            BinaryTreeNode *pNode = dequeTreeNode.front();
            dequeTreeNode.pop_front();
    
            printf("%d ", pNode->m_nValue);
    
            if(pNode->m_pLeft)
                dequeTreeNode.push_back(pNode->m_pLeft);
    
            if(pNode->m_pRight)
                dequeTreeNode.push_back(pNode->m_pRight);
        }
    }

    deque::front返回值是引用(注:因为deque在堆上分配空间,所以可以返回引用。可参考:C++ 引用作为函数返回值)

    但如将代码修改为:

    void PrintFromTopToBottom(BinaryTreeNode* pRoot)
    {
    	if (pRoot == nullptr)
    		return;
    
    	std::deque<BinaryTreeNode *> dequeTreeNode;
    
    	dequeTreeNode.push_back(pRoot);
    
    	while (dequeTreeNode.size())
    	{
    		BinaryTreeNode *&pNode = dequeTreeNode.front(); // 指针的引用
    		dequeTreeNode.pop_front();
    
    		printf("%d ", pNode->m_nValue);
    
    		if (pNode->m_pLeft)
    			dequeTreeNode.push_back(pNode->m_pLeft);
    
    		if (pNode->m_pRight)
    			dequeTreeNode.push_back(pNode->m_pRight);
    	}
    }

    因为pop_front()会析构,所以也会有问题,但可以修改为:

    BinaryTreeNode *&pNode = dequeTreeNode.front(); // 指针的引用
    
    printf("%d ", pNode->m_nValue);
    dequeTreeNode.pop_front();

    即先输出再析构。或者像何老师的代码那样(重新定义一个指针变量pNode,而不是指针引用):

    BinaryTreeNode *pNode = dequeTreeNode.front();
    dequeTreeNode.pop_front();
    
    printf("%d ", pNode->m_nValue);
  • 相关阅读:
    Java基础——数组复习
    JavaScript 笔记总结
    HTML总结
    css代码添加背景图片常用代码
    Java 并发包之线程池综述
    Java 并发之Concurrent 包综述
    AQS 框架之 Lock 接口
    AQS 框架之 LockSupport 线程阻塞工具类
    JAVA 锁之 Synchronied
    ThreadLocal 线程本地变量
  • 原文地址:https://www.cnblogs.com/a3192048/p/12241286.html
Copyright © 2011-2022 走看看