• Binary Tree Preorder Traversal


    Given a binary tree, return the preordertraversal of its nodes' values.

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,2,3]
    

    Follow up: Recursive solution is trivial, could you do it iteratively?


    typedef char ElemType; typedef struct BiTreeNode { ElemType data; struct BiTreeNode *left; struct BiTreeNode *right; }BiTreeNode,*BiTree; Binary Tree Preorder Traversal void TraverseBiTree(BiTree T){ if(T == NULL) return; printf("%c",T->data); TraverseBiTree(T->left); TraverseBiTree(T->right); }

    //非递归方法待完善,以下方法便于理解,如果还是不太理解,不妨画图来看一下,见得多了,抽象能力自然就有了。enjoy!
    Binary Tree Preorder Traversal
    这个方法便于记忆。
    class Solution{
        public:
            vector<int> preorderTraversal(TreeNode* root){
                if(!root) return {};
                vector<int> res;
                stack<TreeNode*> s{{root}};
                while(!s.empty()){
                    TreeNode* t = s.top();s.pop();
                    res.push_back(t->val);
                    if(t->right) s.push(t->right);
                    if(t->left) s.push(t->left);
                }
                return res;
            }
    };
    
    //这个方法可以拓展思路 c
    ++ solution2: class Solution{ public: vector<int> preorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> s; TreeNode *p = root; while(!s.empty() || p){ if(p){ s.push(p); res.push_back(p->val); p = p->left; } else{ TreeNode *t = s.top();s.pop(); p = t->right; } } return res; } };
    
    
    
     
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    shell test条件判断
    shell 变量
    shell 流程结构
    shell 正则表达式
    shell脚本常用参数
    snmp 简单的网络管理协议
    linux
    nmap
    git 基础操作
    linux 下 svn 更新代码
  • 原文地址:https://www.cnblogs.com/hujianglang/p/11421184.html
Copyright © 2020-2023  润新知