94. Binary Tree Inorder Traversal

来源:互联网 发布:中国轻工业出版社 知乎 编辑:程序博客网 时间:2024/05/19 04:54

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].


public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> list=new ArrayList<>();        if(root==null) return list;        Stack<TreeNode>  stack=new Stack<>();        TreeNode p=root;        while(p!=null||!stack.isEmpty()){        while(p!=null){        stack.push(p);        p=p.left;        }        if(!stack.isEmpty()){                //如果p为空,则将p的父亲出栈。否则将p的左子树入栈;        p=stack.pop();        list.add(p.val);        p=p.right;        }        }        return list;    }}


递归:

public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> list=new ArrayList<>();        helper(root,list);        return list;    }    public void helper(TreeNode root,List<Integer> list){    if(root==null) return;    helper(root.left,list);    list.add(root.val);    helper(root.right,list);    }}







0 0
原创粉丝点击