标签: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