首页 > 代码库 > Binary Tree Preorder Traversal
Binary Tree Preorder Traversal
递归实现(python):
# Definition for a binary tree nodeclass 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): 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 treestruct 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。