Binary Tree Inorder Traversal - Leetcode

来源:互联网 发布:终极算法 改变世界 编辑:程序博客网 时间:2024/05/17 08:57

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        Stack<TreeNode> s = new Stack<>();TreeNode pointer = root;ArrayList<Integer> ai = new ArrayList<>();while(pointer!=null || !s.empty()){if(pointer!=null){s.push(pointer);pointer = pointer.left;}else{ai.add(s.peek().val);pointer = s.pop().right;}}return ai;    }}
思路不难,了解就好:1)找到最左边节点,推入链表。栈来辅助中间走过的节点

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

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

confused what "{1,#,2,3}" means?





0 0
原创粉丝点击