【leetcode】Binary Tree Traversal

来源:互联网 发布:js丶稍息 编辑:程序博客网 时间:2024/05/21 07:01

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
这里写图片描述
return [1,2,3].
这道题目就是用递归的方法来做,但是需要调用外部函数进行递归,内部自身递归可能有些问题;
根据访问结点操作发生位置命名:
① NLR:前序遍历(PreorderTraversal亦称(先序遍历))
——访问根结点的操作发生在遍历其左右子树之前。
② LNR:中序遍历(InorderTraversal)
——访问根结点的操作发生在遍历其左右子树之中(间)。
③ LRN:后序遍历(PostorderTraversal)
——访问根结点的操作发生在遍历其左右子树之后。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> path;    void order(TreeNode *root){        if(!root) return;        path.push_back(root->val);        order(root->left);        order(root->right);    }    vector<int> preorderTraversal(TreeNode *root) {        order(root);        return path;    }};

上面的方法是借鉴网上的,先序和后续基本上一致。

Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
这里写图片描述
Given binary tree {1,#,2,3},
千万注意中序遍历是什么。。

class Solution {public:    vector<int> path;    void order(TreeNode *root){        if(!root) return;        order(root->left);        path.push_back(root->val);        order(root->right);    }    vector<int> inorderTraversal(TreeNode *root) {        order(root);        return path;    }};
0 0
原创粉丝点击