首页 > 代码库 > Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

递归实现(python):

# Definition for a  binary tree nodeclass TreeNode:     def __init__(self, x):         self.val = x         self.left = None         self.right = Noneclass Solution:    # @param root, a tree node    # @return a list of integers    def preorderTraversal(self, root):        if root==None :            return []        else:            left=self.preorderTraversal(root.left)            right=self.preorderTraversal(root.right)            mid=[root.val]            res=mid+left+right            return res

 

使用栈(stack)实现(C++):

// Binary Tree Preorder Traversal - do with stack#include<iostream>#include<stack>using namespace std;// Definition for binary treestruct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<int> preorderTraversal(TreeNode *root) {    vector<int> res;    if(root==NULL)        return res;        TreeNode* node=root;    res.push_back(node->val);     stack<TreeNode*> stackNodes;    if(node->right) // 先右子树         stackNodes.push(node->right);    if(node->left) // 后左子树         stackNodes.push(node->left);    while(!stackNodes.empty()){        node = stackNodes.top();        stackNodes.pop();        res.push_back(node->val);        if(node->right)            stackNodes.push(node->right);        if(node->left)            stackNodes.push(node->left);    }     return res;}

参考:https://oj.leetcode.com/discuss/11118/c-solution-with-stack

Binary Tree Preorder Traversal