• [LeetCode] Binary Tree Preorder Traversal


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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,2,3].

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

     解题思路:

    用迭代的方法实现二叉树的遍历,需要借助一些数据结构,比如list,stack等。首先在stack中push入当前的root,由于是前序遍历,故root的value是先于左子树和右子树访问的,故pop取出一个结点,将它的value加入访问序列。之后压入它的右子树和左子树。直到stack为空。

    观察这个过程可以发现,每一个node是最先访问的,然后是其左子树,右子树。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<int> ans;
            list<TreeNode*> node_list;
            if(root == NULL) return ans;
            node_list.push_front(root);
            while(!node_list.empty())
            {
                TreeNode *cur = node_list.front();
                node_list.pop_front();
                ans.push_back(cur -> val);
                if(cur -> right != NULL) node_list.push_front(cur -> right);
                if(cur -> left != NULL) node_list.push_front(cur -> left);
            }
            
            return ans;
        }
    };
  • 相关阅读:
    机器学习-第四讲(模型升级)
    AI人脸匹对
    AI换脸
    人脸识别分析小Demo
    动态规划-线性DP&区间DP
    动态规划-背包问题
    数学知识-博弈论
    数学知识-组合数
    数学知识-扩展欧几里得
    数学知识-欧拉函数&快速幂
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416149.html
Copyright © 2020-2023  润新知