LeetCode.199 Binary Tree Right Side View

来源:互联网 发布:datagridview数据滚动 编辑:程序博客网 时间:2024/06/06 12:46

题目:

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <--- /   \2     3         <--- \     \  5     4       <---

You should return [1, 3, 4].

分析:

/** * 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> rightSideView(TreeNode root) {        //给定一棵二叉树,假设你站在树的右边,返回你从树根到最下面的节点数        //思路:每次都访问右子树,一次从根节点访问到叶子结点。如果右子树不存在,则访问左子树(采用类似层序遍历的方法,每次取每一层的第一个数据)        //注意:需要判断左右子树的高度,来觉得访问结点个数        List<Integer> list=new ArrayList<Integer>();        if(root==null) return list;                Queue<TreeNode> qu=new LinkedList<TreeNode>();        qu.add(root);        while(!qu.isEmpty()){            //每层取第一个数据            int size=qu.size();            //因为size已经是个定值,如果在for中定义,qu的长度会变化,循环长度就不确定了            for(int i=0;i<size;i++){                TreeNode cur=qu.poll();                if(i==0){                    list.add(cur.val);                }                if(cur.right!=null) qu.add(cur.right);                if(cur.left!=null) qu.add(cur.left);            }        }                return list;            }}

分析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> rightSideView(TreeNode root) {        //给定一棵二叉树,假设你站在树的右边,返回你从树根到最下面的节点数        //思路2:采用递归实现,对左右子树高度进行判断。        //注意:需要判断左右子树的高度,来决定访问结点。只有当左右子树高度刚好等于结点所在,才返回该结点的值                List<Integer> list=new ArrayList<Integer>();        if(root==null) return list;        //当前根节点深度为0        backtrace(root,list,0);        return list;    }    //递归实现    public void backtrace(TreeNode root,List<Integer> result,int curDepth){        if(root==null){            return ;        }                if(curDepth==result.size()){            //高度相同            result.add(root.val);        }                //对左右子树递归,每层高度只取一个(一般为最右边的,如若右边不存在,则取左边的)        backtrace(root.right,result,curDepth+1);        backtrace(root.left,result,curDepth+1);    }}


原创粉丝点击