标签:
题目链接:https://leetcode.com/problems/binary-tree-preorder-traversal/
(非递归实现)二叉树的先序遍历。
1 class Solution 2 { 3 public: 4 vector<int> preorderTraversal(TreeNode *root) 5 { 6 vector<int> output; 7 if(root == NULL) 8 { 9 return output; 10 } 11 12 stack<TreeNode*> nodeStack; 13 nodeStack.push(root); 14 15 while(!nodeStack.empty()) 16 { 17 TreeNode *topNode = nodeStack.top(); 18 TreeNode *topleftNode = topNode->left, *toprightNode = topNode->right; 19 output.push_back(topNode->val); 20 nodeStack.pop(); //先pop再push。 21 22 if(toprightNode != NULL) //因为最后访问右边的节点,所以先把右边的节点压入栈。 23 nodeStack.push(toprightNode); 24 if(topleftNode != NULL) 25 nodeStack.push(topleftNode); 26 } 27 28 return output; 29 } 30 };
Leetcode #144 Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/meowcherry/p/4394892.html