zoukankan      html  css  js  c++  java
  • Leetcode No.144 **

    给定一个二叉树,返回它的 前序 遍历。

     示例:

    输入: [1,null,2,3]  
       1
        
         2
        /
       3 
    
    输出: [1,2,3]

    如图输出为:ABDECF

                                             

    解答:参考博客:http://www.cnblogs.com/grandyang/p/4146981.html
    前序遍历、中序遍历、后序遍历是一个系统性的二叉树遍历算法,分别在No.144、No.94、No.145。
    本题依旧可以使用栈来处理。栈是先进后出,而前序遍历的优先级是先左后右,故先压栈右侧指针,再压栈左侧指针。依次循环,最后会得到最左侧值,最后得到最右侧值,满足前序遍历的条件。

    //144
    vector<int> preorderTraversal(TreeNode* root)
    {
        vector<int> res;
        if(root==NULL) return res;
        TreeNode* p;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty())
        {
            p = st.top();
            st.pop();
            res.push_back(p->val);
            if(p->right!=NULL) st.push(p->right);
            if(p->left!=NULL) st.push(p->left);
        }
        return res;
    }//144
  • 相关阅读:
    腾讯安全上海游戏部门笔试题
    2017
    2016
    2015
    2014
    2013
    2012
    2011
    2010
    2009
  • 原文地址:https://www.cnblogs.com/2Bthebest1/p/10851804.html
Copyright © 2011-2022 走看看