Binary Tree Traversal (二)

来源:互联网 发布:小型公司网络搭建案例 编辑:程序博客网 时间:2024/05/21 22:20

Binary Tree Traversal

接上一篇,补充写二叉树的深度优先遍历和广度优先遍历。

1. 深度优先遍历

思路:
二叉树的深度优先遍历,和先序遍历的结果相同,用辅助栈实现,按出栈顺序访问,要先访问左子树,则入栈顺序是右子树、左子树,这样才能出栈时先访问左子树。
代码和上一篇相同。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> depthTraversal(TreeNode* root) {        vector<int> path;        if (root == 0)            return path;        stack<TreeNode *> stk;        stk.push(root);        while (!stk.empty()) {            TreeNode *temp = stk.top();            path.push_back(temp->val);            stk.pop();            if (temp->right)                stk.push(temp->right);            if (temp->left)                stk.push(temp->left);        }        return path;    }};

2. 广度优先遍历

思路:
广度优先遍历,按层次遍历,栈结构已经不能满足要求,所以用队列来实现。出队列时访问。

1 void breadthTraversal(TreeNode *root) {  2     vector<int> path;  3     if (root == 0)  4         return path;  5     queue<TreeNode *> que;  6     que.push(root);  7     while (!que.empty()) {  8         TreeNode *temp = que.front();  9         path.push_back(temp->val); 10         que.pop(); 11         if (temp->left) 12             que.push(temp->left); 13         if (temp->right) 14             que.push(temp->right); 15     }    16     return path; 17 }   
0 0
原创粉丝点击