leetcode 545. Boundary of Binary Tree

xiaoxiao2021-02-28  31

leetcode 545. Boundary of Binary Tree

这一题考察的是树型的先序遍历,三角形正好是先序遍历的访问点,需要做的工作就是识别出是否为边界,在下面的代码中全靠flag变量来处理

参考solution : https://leetcode.com/problems/boundary-of-binary-tree/discuss/

public class Solution{ public List<Integer> boundaryOfBinaryTree(TreeNode root) { List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); getBound(root,left,right,0); left.addAll(right); return left; } public void getBound(TreeNode r, List<Integer> left, List<Integer> right, int flag){ if(r==null) return; if(flag==2) right.add(0,r.val); else if(flag<=1||(r.left==null&&r.right==null)) left.add(r.val); // pre-order if(r.left!=null) getBound(r.left, left, right, flag<=1?1:(flag==2&&r.right==null)?2:3); if(r.right!=null) getBound(r.right, left, right, flag%2==0?2:(flag==1&&r.left==null)?1:3); } }

转载请注明原文地址: https://www.6miu.com/read-36133.html

最新回复(0)