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

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

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

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

    	return result;
    }
};

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

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

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

    	std::stack<TreeNode*> 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<Integer> preorderTraversal(TreeNode root) {
		ArrayList<Integer> result = new ArrayList<Integer>();

		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<Integer> preorderTraversal(TreeNode root) {
		ArrayList<Integer> result = new ArrayList<Integer>();

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

		Stack<TreeNode> nodeStack = new Stack<TreeNode>();
		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/

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值