二叉树的前序、中序、后序遍历

来源:互联网 发布:vscode 编码方式默认 编辑:程序博客网 时间:2024/05/18 22:53

问题描述:给出一棵二叉树返回其节点值得前序遍历

解题思路:写一个递归函数,将每一次遍历的节点放在vector里,前序中序后序遍历完成后,将vector里的值输出即可

实现代码:class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in vector which contains node values.
     */
    vector<int> preorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> vec;
        first(vec,root);
        return vec;
        }
        void first(vector<int> &vec,TreeNode *root){
            if(root==NULL) return;
            else
            {
                vec.push_back(root->val);
                first(vec,root->left);
                first(vec,root->right);
            }
        }
};

class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> vec;
        second(vec,root);
        return vec;
        }
        void second(vector<int> &vec,TreeNode *root){
            if(root==NULL) return;
            else
            {
                second(vec,root->left);
                vec.push_back(root->val);
                second(vec,root->right);
            }
    }
};

class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in vector which contains node values.
     */
public:
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> vec;
        third(vec,root);
        return vec;
    }
    void third(vector<int> &vec,TreeNode *root)
    {   if(root==NULL) return;
    else{
        third(vec,root->left);
        third(vec,root->right);
        vec.push_back(root->val);
      }
    }
};

感悟:递归很好想,就是你得想法把遍历的节点怎么输出,数组输出就行了,不同位置的输出对应不同的便利,改一下输出的位置就好了。

0 0
原创粉丝点击