首页 > 其他 > 详细

94. 二叉树的中序遍历

时间:2020-04-11 22:55:03      阅读:61      评论:0      收藏:0      [点我收藏+]

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
         2
    /
   3

输出: [1,3,2]

/**
 * 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) {
        //迭代 -
        Stack<TreeNode> sta = new Stack<>();
        List<Integer> list = new ArrayList<>();
        while(root != null || !sta.isEmpty()){
            while(root != null){
                sta.push(root);
                root = root.left;
            }
            TreeNode node = sta.pop();
            list.add(node.val);
            //换为右节点
            root = node.right;            
        }
        return list;
    }
}

 

94. 二叉树的中序遍历

原文:https://www.cnblogs.com/zzytxl/p/12682711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!