问题
二叉树的中序遍历。
思路
递归,注意递归的顺序就好了。左节点->父节点->右节点。二叉树的三序遍历,包含前序、中序、后序遍历,这里的顺序指的对象都是父节点。
答案
1. 递归版
c++版,耗时0ms:
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root)
return res;
solve(root,res);
return res;
}
void solve(TreeNode* root, vector<int>&res){
if(!root)
return;
solve(root->left, res);
res.push_back(root->val);
solve(root->right, res);
}
};
java版,用时1ms:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
//special case
if(root==null) return res;
//the terminal condition of the recursion, must have the return value
if(root.left==null&&root.right==null) {
res.add(root.val);
return res;
}
if(root.left!=null) res.addAll(inorderTraversal(root.left));
res.add(root.val);
if(root.right!=null) res.addAll(inorderTraversal(root.right));
return res;
}
}
2. 非递归版
非递归版只能用栈来保存现场,然后利用前进-回溯的思想完成。
java版,耗时2ms:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
if(root==null) return res;
Stack<TreeNode> stack = new Stack();
TreeNode node = root;
while(node!=null){
stack.push(node);
node=node.left;
}
while(stack.size()>0){
TreeNode top = stack.pop();
res.add(top.val);
if(top.right!=null){
node = top.right;
while(node!=null){
stack.push(node);
node = node.left;
}
}
}
return res;
}
}