中序遍历是左子树、根、右子树。这个是同一个规律适用于整个树,所以使用递归。结束条件为没有发现值,即节点为null。
/**
* 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> res=new ArrayList<Integer>();
funcation(root,res);
return res;
}
public void funcation(TreeNode root,List<Integer> res){
if(root==null){
return;
}
funcation(root.left,res);
res.add(root.val);
funcation(root.right,res);
}
}
funcation(root.left,res);
寻找距离root最远的左节点,加入到res集合,否则就直接停止
if(root==null){
return;
}
res.add(root.val);
然后把根加入到res集合
res.add(root.val);
funcation(root.right,res);
寻找距离root最近右节点,加入到res集合,否则就直接停止
res.add(root.val);
栈:先进后出
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
Deque<TreeNode> stacks = new LinkedList<TreeNode>();
while(root!=null||!stacks.isEmpty()){
while(root!=null){
stacks.push(root);
root=root.left;
}
root=stacks.pop();
res.add(root.val);
root=root.right;
}
return res;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务