• 144. Binary Tree Preorder Traversal


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

    Example:

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

    My idea:ricursion

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            res = []
            res.append(root.val)
            if root.left:
                left = self.preorderTraversal(root.left)
                res.extend(left)
            if root.right:
                right = self.preorderTraversal(root.right)
                res.extend(right)
            return res
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            res = []
            res.append(root.val)
            res.extend(self.preorderTraversal(root.left))
            res.extend(self.preorderTraversal(root.right))
            return res

    OTHERS:iretator

    /**
     * Definition for a binary tree node.
     * 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) {
            stack<TreeNode*> s;
            vector<int> ans;
            while(true){
                while(root){
                    ans.push_back(root->val);
                    if(root->right) s.push(root->right);
                    root = root->left;
                }
                if(s.empty()) break;
                root = s.top();
                s.pop();
            }
            return ans;
        }
    };
  • 相关阅读:
    ubuntu13.04中把ibus中的中文拼音输入设为默认
    PHP中获取星期的几种方法
    linux 指令(经常更新)
    手机禁止浏览器往下拉
    Linux常用命令大全
    flask之SQLAlchemy
    【原创】微服务为什么一定要用docker
    flask3
    nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    flask之jinji2模板介绍
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10859248.html
Copyright © 2020-2023  润新知