LeetCode 题解(45): Binary Tree Preorder Traversal

来源:互联网 发布:淘宝海外集运怎么收费 编辑:程序博客网 时间:2024/06/08 17:30

题目:

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?

题解:

C++版

/** * 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) {        stack<TreeNode*> unvisited;        vector<int> preorder;        if(!root)            return preorder;        unvisited.push(root);        while(unvisited.size()) {            TreeNode* current = new TreeNode(0);            current = unvisited.top();            unvisited.pop();            preorder.push_back(current->val);            if(current->right)                unvisited.push(current->right);            if(current->left)                unvisited.push(current->left);        }        return preorder;    }};

Java版

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> preorderTraversal(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        if(root == null)            return result;        Stack<TreeNode> unvisited = new Stack<TreeNode>();        unvisited.push(root);        while(!unvisited.empty()) {            TreeNode current = unvisited.pop();            result.add(current.val);            if(current.right != null)                unvisited.push(current.right);            if(current.left != null)                unvisited.push(current.left);        }        return result;    }}

Python版

# Definition for a  binary tree node# class 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):        result = []        if root == None:            return result        unvisited = [root]        while len(unvisited) != 0:            current = unvisited.pop()            result.append(current.val)            if current.right != None:                unvisited.append(current.right)            if current.left != None:                unvisited.append(current.left)                        return result



0 0