Leetcode94. Binary Tree Inorder Traversal

来源:互联网 发布:淘宝联盟怎么分享赚钱 编辑:程序博客网 时间:2024/06/11 08:37

原题

Given a binary tree, return the inorder traversal of its nodes' values.For example:Given binary tree [1,null,2,3],   1    \     2    /   3return [1,3,2]

题意
中序遍历,将结果返回到list集合中
思路
采用栈的方式,遍历到的节点放在栈里面,直至为空时,再将节点从栈中抛出,遍历其节点的右节点。
代码

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */ /**  * 定义ArrayList,栈和节点,采用中序遍历,  * */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        ArrayList<Integer>list=new ArrayList<Integer>();        if(root==null)return list;        Stack<TreeNode>stack=new Stack<TreeNode>();        TreeNode p=root;        while(!stack.empty()||p!=null){            if(p!=null){                //将节点存在栈中,回头从栈中取出来,再得到该节点的右节点                stack.push(p);                p=p.left;            }            else{                TreeNode t=stack.pop();                list.add(t.val);                p=t.right;            }        }        return list;    }}

原题链接

0 0
原创粉丝点击