94 二叉树的中序遍历
中序遍历就是先访问树的左子树,然后访问根结点,最后访问右子树
中序遍历(非递归)
java代码:
ArrayList用来存储节点数据
当根节点不为空时,则把根结点入栈,然后以它的左子树为根节点继续往下判断(根节点不为空时,则把根结点入栈),直到某个左子女结点为空时,则执行出栈,把出栈的这个结点的数据域数据放入链表;然后再把这个出栈的结点的右子树执行相同的操作,直到结点和栈内元素同时为空,说明遍历结束。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; while(cur!=null || !stack.isEmpty()){ if(cur!=null){ stack.push(cur); cur = cur.left; }else{ cur = stack.pop(); list.add(cur.val); cur = cur.right; } } return list; } }
C++代码:/**
* 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) { stack<TreeNode*> s; vector<int> ans; TreeNode* p = root; while(!s.empty()||p!=NULL){
//这个和后面的效果一样。
if(p!=NULL){
s.push(p);
p = p->left;
}else{
p = s.top();
ans.push_back(p->val);
s.pop();
if(p!=NULL){
p = p->right;
}
}
while(p!=NULL){ s.push(p); p = p->left; } if(!s.empty()){ p = s.top(); ans.push_back(p->val); s.pop(); if(p!=NULL){ p = p->right; } } } return ans; } };
递归法
* 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> ans; TreeNode* p = root; while( p!=NULL ){ inorderTraversal(cur->left); ans.push_back(cur->val); inorderTraversal(cur->right); } return ans; } };