码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Preorder Traversal

时间:2014-10-27 17:21:37      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   color   os   ar   使用   

递归实现(python):

# Definition for a  binary tree node
class TreeNode:
     def __init__(self, x):
         self.val = x
         self.left = None
         self.right = None

class 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 tree
struct 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

标签:des   style   blog   http   io   color   os   ar   使用   

原文地址:http://www.cnblogs.com/iois/p/4054380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!