zoukankan      html  css  js  c++  java
  • leetcode刷题-94二叉树的中序遍历

    非递归 中序遍历的访问顺序是左子树-根-右子树 如果使用非递归 我们需要借助栈来进行实现
    思路:每次访问一个节点 将这个节点看作根节点 可以想象中序遍历的形式 那么我们首先得找到他的左子树的节点,所以得找到
    这个节点的最左子节点 只有他的左子树上的节点全部访问结束了 再访问这个节点 同理 右子树也是相同的道理
    class Solution {
    public List inorderTraversal(TreeNode root) {
    List list = new ArrayList();
    if(rootnull){
    return list;
    }
    Stack stack = new Stack<>();
    while(!stack.isEmpty()||root!=null){
    while(root!=null){
    stack.push(root);
    root = root.left;//找到最左的节点
    }
    TreeNode node = stack.pop();
    list.add(node.val);
    root = node.right;
    }
    return list;
    }
    }
    执行结果:

    方法二:使用递归
    class Solution {
    public List inorderTraversal(TreeNode root) {
    List list = new ArrayList();
    helper(root,list);
    return list;
    }
    public void helper(TreeNode root, List list){
    if(root
    null){
    return;
    }
    helper(root.left,list);
    list.add(root.val);
    helper(root.right,list);
    }
    }

  • 相关阅读:
    栈和队列
    数组的遍历查找
    字符串的子串
    两个字符串
    字符串的遍历
    字符串的替换
    数组和矩阵
    Django 自带的ORM增删改查
    what's the CRSF ??
    Rabbitmq -Publish_Subscribe模式- python编码实现
  • 原文地址:https://www.cnblogs.com/phantom576/p/12655808.html
Copyright © 2011-2022 走看看