LeetCode --- Binary Tree Preorder Traversal

来源:互联网 发布:linux获得root权限 编辑:程序博客网 时间:2024/06/03 20:44

LeetCode --- 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?

先序遍历二叉树。

递归方法:

void PreOrderTraversal(BiTree *root){    if(!root)        return;    cout<<root->data<<endl;    PreOrderTraversal(root->lchild);    PreOrderTraversal(root->rchild);}

非递归遍历:

class Solution {public:    vector<int> preorderTraversal(TreeNode *root) {vector<int>output;vector<TreeNode*>storage;output.clear();storage.clear();if (root == NULL){return output;}TreeNode* temp = root;while (temp != NULL || storage.size() > 0){while (temp != NULL){output.push_back((*temp).val);storage.push_back(temp);temp = temp->left;}if (storage.size() > 0){TreeNode* top = storage.back();storage.pop_back();temp = top->right;}}return output;    }};

相对于后续遍历,先序遍历二叉树要好理解的多。

(1)如果树为空,则直接返回。

(2)将根节点压入到临时存储栈,进入循环。

(3)取栈顶节点,输出该节点值,然后一直循环,将该节点及其左孩子和孩子的左孩子。。。加入到存储栈。

(4)取栈顶节点,出栈,然后将栈顶节点的右孩子赋值给临时节点temp,如果非空,则继续该节点的步骤(3)。如果为空,则会继续取出栈顶元素,出栈。。。。

(5)直到临时存储栈中没有节点位置,出循环,输出结果

0 0