LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)

题目:http://oj.leetcode.com/problems/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?

题目翻译:

给定一个二叉树,返回其节点值的前序遍历。
例如:
给定二叉树{1,#,2,3},
返回[1,2,3]。
注:递归的解法是简单的,你可以用迭代实现呢?
分析:

        使用stack来实现迭代。

C++实现1(递归版):

/**
 * 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 preorderTraversal(TreeNode *root) {
    	vector result;

    	if(root != NULL)
    	{
    		result.push_back(root->val);

    		vector left = preorderTraversal(root->left);
    		result.insert(result.end(), left.begin(), left.end());

    		vector right = preorderTraversal(root->right);
    		result.insert(result.end(), right.begin(), right.end());
    	}

    	return result;
    }
};

C++实现2(迭代版):

class Solution {
public:
    vector preorderTraversal(TreeNode *root) {
    	vector result;

    	if(root == NULL)
    	{
    		return result;
    	}

    	std::stack nodeStack;
    	nodeStack.push(root);

    	while(!nodeStack.empty())
    	{
    		TreeNode *node = nodeStack.top();
    		result.push_back(node->val);
    		nodeStack.pop();

    		if(node->right)
    		{
    			nodeStack.push(node->right);
    		}
    		if(node->left)
    		{
    			nodeStack.push(node->left);
    		}
    	}

    	return result;
    }
};

Java实现1(递归版):

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
		ArrayList result = new ArrayList();

		if (root != null) {
			result.add(root.val);

			result.addAll(preorderTraversal(root.left));

			result.addAll(preorderTraversal(root.right));
		}

		return result;
    }
}

Java实现2(迭代版):

public class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
		ArrayList result = new ArrayList();

		if (root == null) {
			return result;
		}

		Stack nodeStack = new Stack();
		nodeStack.push(root);

		while (!nodeStack.empty()) { 
			TreeNode node = nodeStack.pop();
			result.add(node.val);

			if (node.right != null) {
				nodeStack.push(node.right);
			}

			if (node.left != null) {
				nodeStack.push(node.left);
			}
		}

		return result;
    }
}

Python实现1(递归版):

# 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):
        result = []
        
        if root != None:
            result.append(root.val)
            
            left = self.preorderTraversal(root.left)
            result.extend(left)
            
            right = self.preorderTraversal(root.right)
            result.extend(right)
        
        return result

Python实现2(迭代版):

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def preorderTraversal(self, root):
        result = []
        
        if root == None:
            return result
        
        nodeStack = []
        nodeStack.append(root)
        
        while len(nodeStack) != 0:
            node = nodeStack.pop()
            result.append(node.val)
            
            if node.right != None:
                nodeStack.append(node.right)
            
            if node.left != None:
                nodeStack.append(node.left)
            
        return result

       感谢阅读,欢迎评论!
参考资料:http://www.geeksforgeeks.org/iterative-preorder-traversal/

你可能感兴趣的:(LeetCode)