leetcode 94. Binary Tree Inorder Traversal

来源:互联网 发布:淘宝特卖商城 编辑:程序博客网 时间:2024/05/20 23:04

题目

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

For example:
Given binary tree {1,#,2,3},
这里写图片描述
return [1,3,2].

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

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    //非递归中序     public List<Integer> inorderTraversal(TreeNode root) {//          ///           * 非递归实现中序遍历//           * 中序遍历,先左子树,再根,最后右子树//           *///                      List<Integer> list = new ArrayList<Integer>();            if(root == null)                return list;            TreeNode p = root;            Stack<TreeNode> st = new Stack<>();            while(p != null || !st.isEmpty()){                if(p != null){                    st.push(p);                    p = p.left;                }else{                    p = st.pop();                    list.add(p.val);                    p = p.right;                }            }            return list;        }}

小结

遇到左孩子为空,则该节点可以读,
遇到右孩子为空,则从栈中弹出元素,
将左孩子先压入栈,依次读,

0 0