欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Boundary of Binary Tree

程序员文章站 2022-04-02 18:17:26
...
Input:
  1
   \
    2
   / \
  3   4

Ouput:
[1, 3, 4, 2]

Explanation:
The root doesn't have left subtree, so the root itself is left boundary.
The leaves are node 3 and 4.
The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.
So order them in anti-clockwise without duplicates and we have [1,3,4,2].
Input:
    ____1_____
   /          \
  2            3
 / \          / 
4   5        6   
   / \      / \
  7   8    9  10  
       
Ouput:
[1,2,4,7,8,9,10,6,3]

Explanation:
The left boundary are node 1,2,4. (4 is the left-most node according to definition)
The leaves are node 4,7,8,9,10.
The right boundary are node 1,3,6,10. (10 is the right-most node).
So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].

思路:这题tricky的地方就是,如果从root开始收集好了,会有重复,而且left,leaves,right也会有重复。

怎么避免重复,就是分别收集root.left, root.right两个分支的left, leave,   leave, right;

左右下角重复的点,全部由leave收集,左右两边边不收集root.left == null && root.right == null 的点;

/**
 * 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> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        collectLeft(root.left, list);
        collectLeaves(root.left, list);
        collectLeaves(root.right, list);
        collectRight(root.right, list);
        return list;
    }
    
    private void collectLeaves(TreeNode node,  List<Integer> list) {
        if(node == null) {
            return;
        }
        if(node.left == null && node.right == null) {
            list.add(node.val);
            return;
        }
        collectLeaves(node.left, list);
        collectLeaves(node.right, list);   
    }
    
    private void collectLeft(TreeNode node, List<Integer> list) {
        if(node == null || (node.left == null && node.right == null)) {
            return;
        }
        
        if(node.left != null) {
            list.add(node.val);
            collectLeft(node.left, list);
        } else {
            list.add(node.val);
            collectLeft(node.right, list);
        }
    }
    
    private void collectRight(TreeNode node, List<Integer> list) {
        if(node == null || (node.left == null && node.right == null)) {
            return;
        }
        if(node.right != null) {
            collectRight(node.right, list);
            list.add(node.val);
        } else {
            collectRight(node.left, list);
            list.add(node.val);
        }
    }
}

 

相关标签: traverse