• 94. Binary Tree Inorder Traversal


    Given a binary tree, return the inorder traversal of its nodes' values.

    For example:
    Given binary tree [1,null,2,3],

       1
        
         2
        /
       3
    

    return [1,3,2].

    Note: Recursive solution is trivial, could you do it iteratively?

    本题要求用迭代来做,如果用迭代来解决,就必须使用stack来解决,里面用来存储下一个需要遍历的node,思路是,创建一个stack和TreeNode,让treenode指向当前的节点,先遍历到最左面的节点,将其值存放在list里面,然后遍历该节点右节点,进入下一步循环(值得注意的是,最左面的节点也可以当作是该节点为中节点),代码如下:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> inorderTraversal(TreeNode root) {
    12         List<Integer> res = new ArrayList<Integer>();
    13         Stack<TreeNode> stack = new Stack<TreeNode>();
    14         TreeNode cur = root;
    15         while(cur!=null||!stack.isEmpty()){
    16             while(cur!=null){
    17                 stack.push(cur);
    18                 cur = cur.left;
    19             }
    20             cur = stack.pop();
    21             res.add(cur.val);
    22             cur = cur.right;
    23         }
    24         return res;
    25     }
    26 }
  • 相关阅读:
    datetime模块
    time模块
    shelve模块
    json&pickle 序列化
    re正则
    MQ常用命令
    MQ for linux安装与卸载【转】
    Linux下安装Oracle11g服务器【转】
    PLSQL_数据泵Datapump导入导出数据IMPDP / EXPDP(概念)(Oracle数据导入导出工具)[转]
    [LeetCode]:116:Populating Next Right Pointers in Each Node
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6603168.html
Copyright © 2020-2023  润新知